基本上我正在尝试将我存储在文本文件中的内容用于将其写入.csv文件。在我的文件中是我存储的推文,我试图在.csv文件的每个单元格中有一条推文。
现在它只用一条推文并用它创建一个.csv文件,我需要它来取得所有这些。任何帮助是极大的赞赏。这是我到目前为止所拥有的。
with open('reddit.txt', 'rb') as f:
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
for row in reader:
print row
cr = csv.writer(open('reddit.csv', 'wb'))
cr.writerow(row)
答案 0 :(得分:4)
您需要在循环外创建编写器:
with open('reddit.txt', 'rb') as input_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
with open('reddit.csv', 'wb') as output_file:
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
虽然在这里打开没有with
的文件可能更干净:
input_file = open('reddit.txt', 'rb')
output_file = open('reddit.csv', 'wb')
reader = csv.reader(input_file, delimiter=':', quoting=csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
input_file.close()
output_file.close()
或者您仍然可以使用with
并且只有很长的一行:
with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
答案 1 :(得分:0)
行cr = csv.writer(open('reddit.csv', 'wb'))
位于for循环中。您需要只打开一次文件,将此行放在
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
然后像在每次循环迭代中那样写入它。