我是 python 编程的新手。我有一个 counter.txt 文件,我从中读取计数器值。使用此计数器值,我必须在其他文件夹中创建新文件,例如“/home/pi/data/temp/file%s.txt”%line。
例如:file1.txt、file2.txt 等等。
我为此编写了一些代码,由于某种原因我遇到了以下错误:
IOError: [Errno 22] Invalid argument: '/home/pi/data/temp/file1\n.txt'
我的Python代码如下:
while True:
counter_file = open("counter.txt", 'r+')
line = counter_file.readline()
print(line)
counter_file.close()
file_read = open(r'/home/pi/data/temp/file%s.txt'%line, 'w')
#data_line = line_read.decode("utf-8")
#file_read.write("%s"%data_line)
file_read.close()
counter_file = open("counter.txt", 'w')
line = int(line) + 1
counter_file.write("%s"%line)
counter_file.truncate()
counter_file.close()
当我执行这个时,我得到这个回溯:
File "compute1.py", line 24, in <module>
file_read = open(r'/home/pi/data/temp/file%s.txt'%line, 'w')
IOError: [Errno 22] Invalid argument: '/home/pi/data/temp/file1\n.txt'
请在这方面帮助我。
谢谢!
您需要从line
多变的。这可以通过调用来完成.strip()
在上面。您可以看到文件路径显示为
/home/pi/data/temp/file1\n.txt
当你可能期待它的时候
/home/pi/data/temp/file1.txt
这是因为你的counter.txt
文件使用\n
作为换行符,所以每一行也以它结尾。当你使用readline
,它得到完整的行包括换行符,所以你需要将其删除。尝试将该行替换为
line = counter_file.readline().strip()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)