python find file type and save path and name to txt/csv

Question:

Can anyone help write a script, the goal is to find files with extension and save the name and path in TXT or CSV

that a script which find and print file file type and path,but how can i save the result to csv/txt ?

import fnmatch
import os
import csv

rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
for root, dirs, files in os.walk(rootPath):
    for filepath in fnmatch.filter(files, pattern):
        x = (os.path.join(root, filepath))
        print(x)

i try this one, but its save only the last line.

import fnmatch
import os
import csv

rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
for root, dirs, files in os.walk(rootPath):
    for filepath in fnmatch.filter(files, pattern):
        x = (os.path.join(root, filepath))
        file = open(filepath, 'w')
        file.write(x)
file.close()
print(x)
Asked By: Maximus

||

Answers:

from glob import glob
import os

files = sorted(glob(os.path.join(rootPath, pattern)))

with open(filepath, 'w') as fid:
    fid.write('n'.join(files))

Answered By: Arturo Mendoza

I think the reason is you always open the file within loop using open(filepath, 'w') the option ‘w’ is always overwrite the file, if you want to append, you can use ‘a’, but I think in this case is not good solution because the main reason is you always reopen the file for each loop

By using your code, I think you can solve it by putting the open command outside the loop

import fnmatch
import os
import csv

rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
file = open(filepath, 'w')

for root, dirs, files in os.walk(rootPath):
    for filepath in fnmatch.filter(files, pattern):
        x = (os.path.join(root, filepath))
        file.write(x+'n')

file.close()
Answered By: d_frEak
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.