Sam*_*oor 4 file-io python-3.x raspberry-pi
我是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'
Run Code Online (Sandbox Code Playgroud)
我的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()
Run Code Online (Sandbox Code Playgroud)
当我执行这个,我得到这个追溯:
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'
Run Code Online (Sandbox Code Playgroud)
请帮助我这方面.谢谢!
您需要从line变量中删除尾随换行符.这可以通过调用.strip()它来完成.你可以看到文件路径出来了
/home/pi/data/temp/file1\n.txt
Run Code Online (Sandbox Code Playgroud)
当你可能期待它的时候
/home/pi/data/temp/file1.txt
Run Code Online (Sandbox Code Playgroud)
这是因为您的counter.txt文件\n用作换行符,因此每行也以它结尾.使用时readline,它会获得包括换行符在内的整行,因此您需要将其删除.尝试用.替换该行
line = counter_file.readline().strip()
Run Code Online (Sandbox Code Playgroud)