0

我对python很陌生,我正在尝试:

  • 在用户定义的目录中(1000 个图像)
  • 查找文件名(已完成)
  • 查找文件大小(已完成)
  • 存储到数组
  • 将数组存储到文本文件

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)

4

4 回答 4

0

some notes about the below implementation:

  • generally always use the csv library because it properly handles special csv characters like commas and quotes. It can be really messy if you will do this escaping by hand.
  • it's better not to hard code path delimiter like /, the above two answers won't work on windows machines. By using os.path.join your code will run correctly on all platforms.

code:

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)
于 2012-10-02T08:24:54.300 回答
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 可以很好地相互配合,因此导入它应该不会有任何问题。

于 2012-10-02T07:37:49.557 回答
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 模块,但我认为对于这样一个简单的文件来说它是多余的。如果您有兴趣使用它,它看起来像这样:

import csv
with open('myoutputfile.csv', 'wb') as outputFile:
    csvwriter = csv.writer(outputFile, dialect='excel')
    for entry in data:
        csvwriter.writerow(entry)
于 2012-10-02T07:26:42.010 回答
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)
于 2012-10-02T08:28:03.247 回答