python讀取文件時\n問題處理


存在如下配置文件1.txt

123456
09876

with open('1.txt', 'r', encoding="utf-8") as f:
conds = []
for i in range(2):
conds.append(f.readline())
print(conds)
輸出為 ['123456\n', '09876\n']

with open('1.txt', 'r', encoding="utf-8") as f:
conds = []
for i in range(2):
conds.append(f.readline())
print(conds[0])
輸出為 123456
誤以為 \n 已經被自動過濾掉了

由於需要在文件里面獲取信息與其他信息作比較,發現結果與預期不符
with open('1.txt', 'r', encoding="utf-8") as f:
conds = []
for i in range(2):
conds.append(f.readline())
if conds[0] in '123456789':
print(1)
else:
print(0)
以為會輸出1,結果輸出0
遂發現\n實際是生效的
修正后為
with open('1.txt', 'r', encoding="utf-8") as f:
conds = []
for i in range(2):
conds.append(f.readline().rstrip('\n'))
if conds[0] in '123456789':
print(1)
else:
print(0)
輸出1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM