对目录中的所有文件运行 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2609159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:03:37  来源:igfitidea点击:

Running a python script on all the files in a directory

pythoncommand-linescripting

提问by S1syphus

I have a Python script that reads through a text csv file and creates a playlist file. However I can only do one at a time, like:

我有一个 Python 脚本,它读取一个文本 csv 文件并创建一个播放列表文件。但是我一次只能做一个,比如:

python playlist.py foo.csv foolist.txt

However, I have a directory of files that need to be made into a playlist, with different names, and sometimes a different number of files.

但是,我有一个需要制作成播放列表的文件目录,具有不同的名称,有时还有不同数量的文件。

So far I have looked at creating a txt file with a list of all the names of the file in the directory, then loop through each line of that, however I know there must be an easier way to do it.

到目前为止,我已经创建了一个 txt 文件,其中列出了目录中文件的所有名称,然后遍历其中的每一行,但是我知道必须有一种更简单的方法来做到这一点。

回答by falstro

for f in *.csv; do
  python playlist.py "$f" "${f%.csv}list.txt"
done

Will that do the trick? This will put foo.csv in foolist.txt and abc.csv in abclist.txt.

这会奏效吗?这将把 foo.csv 放在愚蠢的.txt 中,将 abc.csv 放在 abclist.txt 中。

Or do you want them all in the same file?

或者你希望它们都在同一个文件中?

回答by Daniel DiPaolo

Just use a for loop with the asterisk glob, making sure you quote things appropriately for spaces in filenames

只需使用带有星号 glob 的 for 循环,确保为文件名中的空格正确引用内容

for file in *.csv; do
   python playlist.py "$file" >> outputfile.txt;
done

回答by Daniel DiPaolo

Is it a single directory, or nested?

它是单个目录还是嵌套目录?

Ex.

前任。

topfile.csv
topdir
   --dir1
       --file1.csv
       --file2.txt
       --dir2
           --file3.csv
           --file4.csv

For nested, you can use os.walk(topdir)to get all the files and dirs recursively within a directory.

对于嵌套,您可以使用os.walk(topdir)递归获取目录中的所有文件和目录。

You could set up your script to accept dirs or files:

您可以将脚本设置为接受目录或文件:

python playlist.py topfile.csv topdir

python playlist.py topfile.csv topdir

import sys
import os

def main():
    files_toprocess = set()
    paths = sys.argv[1:]
    for p in paths:
        if os.path.isfile(p) and p.endswith('.csv'):
            files_toprocess.add(p)
        elif os.path.isdir(p):
            for root, dirs, files in os.walk(p):
                files_toprocess.update([os.path.join(root, f) 
                                        for f in files if f.endswith('.csv')])

回答by SilentGhost

if you have directory name you can use os.listdir

如果你有目录名,你可以使用 os.listdir

os.listdir(dirname)

if you want to select only a certain type of file, e.g., only csv file you could use globmodule.

如果您只想选择某种类型的文件,例如,只有 csv 文件,您可以使用glob模块。