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