尝试使用 Python 从目录中获取所有文件(包括只读文件)

Trying to fetch all the files (including read only) from a directory using Python

我是 Python 的新手 - 如果我的问题看起来很愚蠢,请原谅。

我正在尝试获取给定文件夹中存在的所有文件并创建一个显示文件名和路径的 Excel。

它在某些文件夹上工作正常,但不是全部。我认为的原因可能是它无法获取处于只读模式的数据(我不太确定)。

这是我得到的错误:

F:/
Traceback (most recent call last):
File "c:/Vamsi_Folder/4.Tutorials/Python/OS/01-WIP/Get Files From Directory/Get_Files_From_Directory.py", line 36, in
List = getListOfFiles(filename)

File "c:/Vamsi_Folder/4.Tutorials/Python/OS/01-WIP/Get Files From Directory/Get_Files_From_Directory.py", line 30, in getListOfFiles
allFiles = allFiles + getListOfFiles(fullPath)

File "c:/Vamsi_Folder/4.Tutorials/Python/OS/01-WIP/Get Files From Directory/Get_Files_From_Directory.py", line 22, in getListOfFiles
listOfFile = os.listdir(dirName)

PermissionError: [WinError 5] Access is denied: 'F:/System Volume Information'

这是我使用的代码:

#program to write files from directory in Excel


import os
from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
import numpy as np
from tkinter import Tk
from tkinter.filedialog import askdirectory
from tkinter.filedialog import asksaveasfilename
import ntpath


Tk().withdraw()
filename = askdirectory()
print(filename)


def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)

    return allFiles

List = getListOfFiles(filename)
Filename = []
for i in List:
    Filename.append(ntpath.basename(i))


workbook = Workbook()
worksheet = workbook.active
worksheet.title = "Directory"

outlist = [Filename,List]

transpose = np.array(outlist).T
transpose_outlist = transpose.tolist()

worksheet.append(["Filename","Path"])

for row in transpose_outlist:
    worksheet.append(row)

count = "A1:""B"+str(len(List)+1)

tab = Table(displayName="Directory", ref=count)
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
                       showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
worksheet.add_table(tab)

savename =asksaveasfilename(initialdir = "/",defaultextension="*.*",filetypes=\
                                     (("xml files","*.xml"),\
                                      ('xlsx files','.xlsx'),\
                                      ("all files","*.*")))

workbook.save(savename)

您无权访问 'System Volume Information' 硬盘分区。 How to gain access to the System Volume Information folder

其次,在我看来,这是一个更好的(pythonic)代码,用于获取目录及其子目录中所有文件的列表。

import os
import csv

directory = r'F:/'

files_list = [d + '\' + f for d, dirs, files in os.walk(directory) for f in files]

with open('dicrectory_files.csv', 'w', newline='') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(['basename', 'filepath'])
    for file in files_list:
        csv_writer.writerow([os.path.basename(file), file])

然后就可以直接在Excel中打开这个CSV了。

如果您不想在代码中直接输入目录路径,那么您可以使用以下更改目录路径分配语句。

directory = input('Enter directory path: ')
if directory == '':
    directory = os.getcwd()

那么当你运行代码文件(.py)时,你只需要在提示符window中复制并粘贴你要走的目录路径即可。 CSV 文件将在您的代码文件的目录中创建。