python readline或者readlines添加'\n'问题

来源:互联网 发布:孙鑫windows编程视频 编辑:程序博客网 时间:2024/06/14 17:07

今天读取文件时eclipse报错,

IOError: [Errno 2] No such file or directory: '/home/xxx/images/xx.jpg\n'

然后我反复对照自己本地的路径仔细检测了几遍,都没发现问题。期间进行了测试,代码如下:

print(os.path.isfile('/home/xxx/images/xx.jpg'))print(os.path.isfile('/home/xxx/images/xx.jpg\n'))print(os.path.isfile(src_path))
结果是

TrueFalseTrue

原来我的文件名从txt中读取得到,readline或者readlines会添加'\n'到字符后面,解决方法如下:

line = line.rstrip('\n')

参考链接:

https://stackoverflow.com/questions/11280282/to-read-line-from-file-in-python-without-getting-n-appended-at-the-end


原创粉丝点击