Running python script for all files in a directory

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

python playlist.py foo.csv foolist.txt 

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

So far, I have looked at creating a txt file with a list of all the file names in the directory, and then scrolling through each line, but I know there should be an easier way to do this.

+4
source share
4 answers
 for f in *.csv; do python playlist.py "$f" "${f%.csv}list.txt" done 

Will it be a trick? This will result in foo.csv in the file foolist.txt and abc.csv in abclist.txt.

Or do you want all of them to be in one file?

+7
source

Just use a for loop with an asterisk asterisk, making sure you quote things correctly for spaces in file names

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

Is this the only directory or subdirectory?

Ref.

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

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

You can configure the script to accept files or files:

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')]) 
+3
source

if you have a directory name you can use os.listdir

 os.listdir(dirname) 

if you want to select only a certain type of file, for example, only a csv file, you can use glob .

+2
source

Source: https://habr.com/ru/post/1306494/


All Articles