【问题标题】:Running Python script over multiple files in a folder [closed]在文件夹中的多个文件上运行 Python 脚本 [关闭]
【发布时间】:2014-09-15 19:06:02
【问题描述】:

我在 opensuse 中使用 python,我的问题是我需要在我的文件夹中执行大数据。 例如

python myprogram.py 20140101.txt

我仍然需要运行大量具有类似命名 (20140101.txt) ex 20140204 等的数据。 我的问题是如何让我的程序自动为所有数据一起运行。

【问题讨论】:

  • 大家好,感谢您的关注。我的代码现在可以工作了。正确的答案是 data/*.txt 中的文件 do python myprogram.py $file;完成了,非常感谢大家

标签: python linux opensuse


【解决方案1】:

像这样使用 bash:

for file in /dir/*.txt
do
    python myprogram.py $file     
done

【讨论】:

  • chers...我试试你的建议,但我不清楚为什么只能执行我的最后一个数据。
【解决方案2】:

对于纯 python 解决方案,请查看fileinput

它是 python 标准库的一部分,让我们循环遍历通过标准输入或文件列表给出的文件,例如:

import fileinput
for line in fileinput.input():
    process(line)

所以你可以这样做:

./python myprogram 2014*.txt

【讨论】:

    【解决方案3】:

    glob 模块对于处理具有不同名称的多个文件很有用。

    https://docs.python.org/2/library/glob.html

    【讨论】:

    • 谢谢我会找到一些教程
    【解决方案4】:

    python 解决方案是使用“glob”。它可以帮助您根据特定模式创建文件名列表。然后,您可以遍历这些文件名以执行您的命令。请参见下面的示例。

    import glob
    
    txt_files = glob.glob("201401*.txt")
    
    for txt in txt_files:
        print txt
        my_txt_file = open(txt, "r") 
    

    进一步参考: https://docs.python.org/3/library/glob.htm

    【讨论】:

    • 啊这对我来说是新的,我试试吧
    猜你喜欢
    • 2018-01-06
    • 2015-09-03
    • 2014-06-11
    • 2020-05-08
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多