对不起,我是Python 3的新手,我已经在这里一直在寻找答案,但是我找不到我的问题的具体答案,我可能没有问正确的问题。
我有一个名为test5.txt的文件,在该文件中,我编写了要使用Python打开/读取的文件的文件名,即(test2.txt、test3.txt和test4.txt),这些txt文档上有随机的单词。
这是我的代码:
with open("test5.txt") as x:
my_file = x.readlines()
for each_record in my_file:
with open(each_record) as y:
read_files = y.read()
print(read_files)但遗憾的是,我错了:"OSError: [Errno 22] Invalid argument: 'test2.txt\n'"
发布于 2018-10-06 06:13:47
each_record似乎包含一个换行符\n字符。您可以尝试在将文件字符串作为文件打开之前删除它。
with open("test5.txt") as x:
my_file = x.readlines()
for each_record in my_file:
with open(each_record.strip()) as y:
read_files = y.read()
print(read_files)发布于 2018-10-06 09:14:59
建议使用rstrip而不是strip --最好是安全和明确的。
for each_record in my_file:
with open(each_record.rstrip()) as y:
read_files = y.read()
print(read_files)但是,使用str.splitlines方法,这也应该是可行的,而且可能更漂亮--参见下面的here。
with open("test5.txt") as x:
list_of_files = x.read().splitlines()https://stackoverflow.com/questions/52676189
复制相似问题