python 查找文件类型并将路径和名称保存到 txt/csv

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

谁能帮忙写个脚本,目标是找到带扩展名的文件,把名字和路径保存成TXT或CSV

那个查找和打印文件文件类型和路径的脚本,但是我怎样才能将结果保存到 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)

我试试这个,但它只保存了最后一行。

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)
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))

我认为原因是您总是使用 open(filepath, 'w') 在循环内打开文件,选项 'w' 总是覆盖文件,如果您想追加,可以使用 'a' , 但我认为在这种情况下不是好的解决方案,因为主要原因是你总是为每个循环重新打开文件

通过使用你的代码,我认为你可以通过将打开命令放在循环之外来解决它

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()