I have different subdirectories with same file names in each directory. (20 files in each folder)
For example:
FolderA:
1.txt
2.txt
3.txt
FolderB:
1.txt
2.txt
3.txt
FolderC:
1.txt
2.txt
3.txt
and so on
I want to write the paths of same file in each folder to a csv file. Output should have 20 csv files with paths
I’m a newbie to Python.Can someone please help me this.
Thanks
Example Output:
output_1.csv
path/to/FolderA/1.txt
path/to/FolderB/1.txt
path/to/FolderC/1.txt
output_2.csv
path/to/FolderA/2.txt
path/to/FolderB/2.txt
path/to/FolderC/3.txt
Given:
C:FILES
├───FolderA
│ 1.txt
│ 2.txt
│ 3.txt
│
├───FolderB
│ 1.txt
│ 2.txt
│ 3.txt
│
└───FolderC
1.txt
2.txt
3.txt
You can use the pathlib
module to recursively collect files. I am assuming you want the base filename to be part of the output name. The .stem
attribute is the base filename without extension.
from pathlib import Path
# Delete output files if they already exist.
for filename in Path(r'.').glob('output_*.csv'):
filename.unlink()
# For each text file, append its absolute path to the appropriate file.
for filename in Path(r'c:files').rglob('*.txt'):
with open(f'output_{filename.stem}.csv', 'a') as fout:
print(filename.absolute(), file=fout)
Outputs:
output_1.csv
c:filesFolderA1.txt
c:filesFolderB1.txt
c:filesFolderC1.txt
output_2.csv
c:filesFolderA2.txt
c:filesFolderB2.txt
c:filesFolderC2.txt
output_3.csv
c:filesFolderA3.txt
c:filesFolderB3.txt
c:filesFolderC3.txt
I feel like you should use a for loop, eg:
Import os
Folder_num = 1
For i in range(20#<- number of folders):
Parent = Folder
X = 0
For i in range(3#<-number of files in folder):
Print(os.listdir(path)[x])#prints path to first file in directory
X+= 1
Folder_num += 1
This might not work because I didn’t have time to check and debug it, but hopefully you get the main idea.
1