Python 3.2:IOError:[Errno 22]无效的参数:'/home/pi/data/temp/file1\n.txt'

4
我是一个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'

请在这方面帮助我。谢谢!
2个回答

6

您需要从line变量中删除尾随换行符。这可以通过对其调用.strip()来完成。您可以看到文件路径是这样出现的:

/home/pi/data/temp/file1\n.txt

当你可能期望它是这样时
/home/pi/data/temp/file1.txt

这是因为你的counter.txt文件使用\n作为换行符,因此每行末尾也包含它。当你使用readline时,它会获取完整的一行,包括换行符,因此你需要将其去除。试着用以下语句替换该行:
line = counter_file.readline().strip()

1
虽然如此,\n是文件名中有效的字符,不会导致fopen(2)结果为EINVAL - Ignacio Vazquez-Abrams

0
该进程无法写入该目录中的文件。要么使进程可以写入,要么将其写入其他位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接