【问题标题】:Open files using For-loop (Python 3)使用 For 循环打开文件 (Python 3)
【发布时间】:2018-10-06 06:02:54
【问题描述】:

对不起,我是 Python 3 的新手,我已经在 SO 中一直在寻找答案,但我找不到我的问题的具体答案,而是我可能没有问正确的问题。

我有一个名为 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'"

【问题讨论】:

  • 你检查过这个post吗?

标签: python python-3.x


【解决方案1】:

建议使用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()

【讨论】:

    【解决方案2】:

    似乎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)
    

    【讨论】:

    • 成功了!谢谢你的数字!我已经工作了 4 个小时来解决这个问题 :) .strip() 就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2013-04-06
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多