【问题标题】:Run a loop over several different file paths在几个不同的文件路径上运行循环
【发布时间】:2019-11-22 13:27:18
【问题描述】:

我在一个名为 list_paths 的文本文档中有一个文件路径列表,看起来像这样(顺便说一句,文档中没有空行):

/users/myname/Documents/test1.txt 
/users/myname/Documents/test2.txt 
/users/myname/Documents/test3.txt 
/users/myname/Documents/test4.txt

我有一个使用文本文件的工作代码,但我希望它转到该文件(列表路径)并循环遍历每个特定路径以获取信息,这样我就不必单独输入它们。

类似的东西:

with open(list_paths, "r") as file:
for line in file:
    line.strip("\n")
    fp = line      

with open(fp, "r") as file:
[The rest of my code]

这样我的代码就可以在每个特定文件上运行,而无需我手动放入每个文件路径。

【问题讨论】:

  • 您的问题是什么?你有一个几乎可以工作的代码,有什么问题?

标签: python loops file path


【解决方案1】:

您可以使用readlines 函数简单地读取文件的路径, 然后打开它们中的每一个

with open(file_list_path, "r") as flp:
    files_list = flp.readlines()
    for file in files_list:
        with open(file, "r") as f:
        # your stuff here for each file(f)

【讨论】:

    【解决方案2】:

    \n 字符的条带没有到位!

    with open(list_paths, "r") as file1:
        for line in file1:
            fp = line.strip("\n")
            with open(fp, "r") as file2:
                [The rest of my code]
    

    【讨论】:

    • 我收到错误后的错误,知道如何解决它吗?:[Errno 1] Operation not allowed: '/Users/karel/Documents/test1.txt'
    • @helpmeplease 这真的取决于你的其余代码,我怎么知道你在做什么? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多