我是python的新手,我正在尝试:
from Tkinter import Tk
from tkFileDialog import askdirectory
from array import *
import os
Tk().withdraw()
fileDir = askdirectory()
print(fileDir)
dirList=os.listdir(fileDir)
for fname in dirList:
print fname
print os.path.getsize(fileDir+"/"+fname)
答案 0 :(得分:0)
要在元组中存储文件名和大小并将它们写入文本文件,您可以执行以下操作:
from Tkinter import Tk
from tkFileDialog import askdirectory
from array import *
import os
Tk().withdraw()
fileDir = askdirectory()
print(fileDir)
dirList = os.listdir(fileDir)
data = ((fname, str(os.path.getsize(fileDir + "/" + fname))) for fname in dirList)
outputFile = open('myoutputfile.csv', 'w')
for entry in data:
outputFile.write(','.join(entry) + '\n')
outputFile.close()
在我的python安装目录上运行它会给出一个如下所示的文件:
DLLs,4096
Doc,0
include,32768
Lib,65536
libs,4096
LICENSE.txt,40080
NEWS.txt,285115
python.exe,27136
pythonw.exe,27648
README.txt,54967
Scripts,0
tcl,4096
Tools,4096
你应该可以在Excel中打开.csv文件没问题。请注意,如果文件名中的任何一个包含逗号,新行等,则可能需要引用文件名。
对于更重要的东西,有csv module,但我认为对于这样一个简单的文件来说太过分了。如果您有兴趣使用它会看起来像这样:
import csv
with open('myoutputfile.csv', 'wb') as outputFile:
csvwriter = csv.writer(outputFile, dialect='excel')
for entry in data:
csvwriter.writerow(entry)
答案 1 :(得分:0)
你可能想做这样的事情:
#!/usr/bin/env python
import csv, os
OUT = 'files_and_sizes.csv'
DIR = '<some directory>'
def main():
writer = csv.writer(open(OUT, 'w'))
for f in os.listdir(DIR):
if os.path.isfile(DIR+ '/' + f):
writer.writerow([f, os.path.getsize(DIR + '/' + f)])
if __name__ == '__main__':
main()
CSV和Excel相互配合使用,因此您输入它时不会有任何问题。
答案 2 :(得分:0)
关于以下实施的一些说明:
代码:
from tkFileDialog import askdirectory
from glob import glob
from os import listdir
from os.path import join, getsize
import csv
CSV_FILE = 'listing.csv'
path = askdirectory()
files = listdir(path)
rows = [(i, getsize(join(path, i))) for i in files]
with open(CSV_FILE, 'wb') as f:
writer = csv.writer(f)
writer.writerows(rows)
答案 3 :(得分:0)
#!/usr/bin/env python
import csv
import os
from Tkinter import Tk
from os.path import join, getsize
from tkFileDialog import askdirectory
# get directory path
root = Tk()
root.withdraw()
dirpath = askdirectory()
root.destroy()
# save filename, file size entries for the directory in csv format
entries = ((fn, getsize(join(dirpath, fn))) for fn in os.listdir(dirpath))
with open('entries.csv', 'wb') as file:
csv.writer(file).writerows(entries)