嗨,我是关于python的新手,
我有2000个公司名单,我想在我的网站上分享。 我能够使用python脚本导入我的csv文件。 这是我的代码:
import csv
with open('test.csv', 'r') as csvfile:
r = csv.reader(csvfile, delimiter=',')
for row in r:
print (row)
您能帮我解决一下如何将其打印到文件中吗?
谢谢!
答案 0 :(得分:1)
import csv
with open('test.csv', 'r') as csvfile:
r = csv.reader(csvfile, delimiter=',')
with open(file_path,"w") as text_file:
for row in r:
text_file.write(row+"\n")
在使用增量编号生成的单独文件中打印每一行
with open('test.csv', 'r') as csvfile:
r = csv.reader(csvfile, delimiter=',')
cnt=0
for row in r:
cnt+=1
file_path="text_file %s.txt" % (str(cnt),)
with open(file_path,"w") as text_file:
text_file.write(row+"\n")
答案 1 :(得分:1)
我喜欢repzero的回答,但需要将行转换为str()
import csv ## import comma separated value module
以只读模式打开test.csv作为变量csvfile
with open('test.csv', 'r') as csvfile:
将变量csvdata设置为从csvfile读取的所有数据,
每次发现逗号时拆分
csvdata = csv.reader(csvfile, delimiter=',')
以写入模式打开test.txt作为变量text_file
with open(test.txt, 'w') as text_file:
遍历csv数据的每一行
for row in csvdata:
将数据行转换为文本字符串,
并将其写入文件,然后是换行符
text_file.write(str(row) + '\n')
答案 2 :(得分:0)
使用file object创建open()
,写入,然后关闭它。
file = open("path/to/file.txt", "w+")
for row in r:
file.write(row)
file.close()
答案 3 :(得分:0)
与其他答案不同,您实际上可以"打印"直接使用相同的关键字print
到文件。通过重新路由文件方法:
import csv
with open('test.csv') as csvfile, open("yourfilepath.txt", "w") as txtfile:
r = csv.reader(csvfile, delimiter=',')
for row in r:
print (row, file = txtfile)