Desktop.zip包含多个文本文件。 fun.py是一个python程序,它将打印zip文本文件的名称以及每个文件中的行数。一切都很好,直到这里。但是,它也会将此输出导入到一个CSV文件中。代码: -将输出导入CSV文件
import zipfile, csv
file = zipfile.ZipFile("Desktop.zip", "r")
inputcsv = input("Enter the name of the CSV file: ")
csvfile = open(inputcsv,'a')
#list file names
for name in file.namelist():
print (name)
# do stuff with the file object
for name in file.namelist():
with open(name) as fh:
count = 0
for line in fh:
count += 1
print ("File " + name + "line(s) count = " + str(count))
b = open(inputcsv, 'w')
a = csv.writer(b)
data = [name, str(count)]
a.writerows(data)
file.close()
我期待在CSV输出文件,如: -
test1.txt, 25
test2.txt, 10
但我得到这个输出CSV文件: -
t,e,s,t,1,.,t,x,t
2,5
t,e,s,t,2,.,t,x,t
1,0
这里,test1.txt的和test2.txt是Desktop.zip中的文件,25和10分别是这些文件的行数。
在你的问题中的代码不可能已经产生你说做的csv文件。 – martineau