python代码不会生成csv文件

时间:2017-07-21 08:19:56

标签: python csv standard-library

AIM:我想在各种硬盘上记录所有文件并收集文件名,文件夹和文件大小(以兆字节为单位)。代码运行,据我所知不会产生任何错误,但最终不会产生csv文件?

我尝试了什么: 我尝试用Sudo运行文件,用chmod + x更改权限,检查python是否在标准用户和sudo用户的相同位置,最后删除或注释掉麻烦的​​行,这些行似乎产生不同的结果或错误取决于操作系统。

import os
from os import path
import sys
import datetime
from datetime import date, time, timedelta
import time
import csv
#from socket import gethostbyname

#variables
#hostname = str(socket.gethostname())
scandir = "/"
savefiledir = "/Users/joshua/Documents/python/"
textfilename = str(datetime.datetime.now().strftime("%Y-%m-%d")) + "_" "directory_printer.csv"

#change directory to the root directory or the one which you want to scan for files (scandir)
os.getcwd()
os.chdir(scandir)
directory = os.getcwd()

#find all files in a directory and it's sub directory regardless of extension
results = [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(directory)] for val in sublist]

d = {}
file_count = 0
metadata = []

for file in results:
    #full path
    try:
        fullpath = file
    except:
        fullpath = None

    #file name
    try:
        file_directory = "/".join(str(file).split('/')[1:-1])
    except:
        file_directory = None

    #file extension
    try:
        file_ext = str(file).split('/')[-1]
    except:
        file_ext = None

    #subfolders
    try:
        parts = file_directory.split('/')
        sub_folders = ":".join(parts[1:-1])
    except:
        sub_folders = None

    #num subfolders
    try:
        count_subfolders = len(sub_folders.split(':'))
    except:
        count_subfolders = None

    #filesize megabytes
    try:
        filesize_mb = os.path.getsize(file)/1024
    except:
        filesize_mb = None

    #date modified
    try:
        date_modified = datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime(file))
    except:
        date_modified = None

    #time modified
    #try:
#        time_modified = os.stat(fullpath).st_mtime #time of most recent content modification
    #except:
#        time_modified = None


    #time created (windows)
#    try:
#        time_created = os.stat(fullpath).st_ctime #platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)#    except:
#        time_created = None

    #record all file metadata
    d[file_count] = {'Full_Path': fullpath, 'File_Directory': file_directory,
                     'File_Extension': file_ext, 'List_Sub_Folders' : sub_folders,
                    'Count_Sub_Folders' : count_subfolders, 'Filesize_mb' : filesize_mb,
                     'Date_Modified' : date_modified}

    file_count = file_count + 1

#write the dictinary with the disks file metadata to a csv file
with open(textfilename,'w') as f:
    w = csv.writer(f)
    w.writerows(d.items())

print("Scanning directory: "
      + str(scandir) + " complete!" + "\n"
      + "The results have been saved to: " + "\n"
      + str(savefiledir)+str(textfilename))

1 个答案:

答案 0 :(得分:1)

实际上,您的代码看起来会将CSV文件写入scandir/),而不是savefiledir,因为在程序开头您调用{{ 1}}。如果您想将文件放在正确的位置(最终打印的消息显示保存到的位置),您应该这样做:

os.chdir(scandir)