我是 python 新手,但我在 Stack Overflow、google 和 CodeAcademy 上搜索了我明显非常简单的问题的答案或灵感。我认为找到一个使用 for 循环来保存每次交互的简单示例很容易找到,但我要么错过了它,要么没有词汇来提出正确的问题。所以请不要在显示器前对这个简单的问题大声叹息。谢谢。
我想简单地编写一个 csv 文件,其中包含下面代码中单独列中的两个打印行的每次迭代。因此输出示例可能如下所示:
################## andy.dat, 8 brett.dat, 9 candice.dat, 11 #################
the code I have so far is:
import sys
import os.path
image_path = "C:\\"
for filename in os.listdir (image_path):
print filename
print len(filename)
如果我尝试这样做
x = filename
然后我只得到写入 x 的循环的最后一个迭代。如何使用 for 循环将它们全部写入 x ?另外,如何将其写为 csv 中的一列,并在其旁边显示 len(filename) 的打印结果?谢谢。
最佳答案
尽管对于此任务,您不需要它,但如果可以的话,我会利用标准库模块,例如 csv
。尝试这样的事情,
import os
import csv
csvfile = open('outputFileName.csv', 'wb')
writer = csv.writer(csvfile)
for filename in os.listdir('/'): # or C:\\ if on Windows
writer.writerow([filename, len(filename)])
csvfile.close()
关于python - 从 for 循环和列表写入 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15727084/