将python脚本打印到文件

问题描述:

嗨,我是一个关于python的新手,将python脚本打印到文件

我有2000个公司名单,我想在我的网站上分享。 我能够使用python脚本导入我的csv文件。 这是我的代码:

import csv 

with open('test.csv', 'r') as csvfile: 
    r = csv.reader(csvfile, delimiter=',') 
    for row in r: 
     print (row) 

你帮我,我怎么可以打印此到一个文件?

谢谢!

+2

只要使用“打开”打开一个文件,并将其写入 – chbchb55

+0

你想要什么格式,它被写在 – chbchb55

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") 
+0

感谢分享! –

+0

您有关于如何将每行打印到单独文件(txt)的提示 –

+0

好吧,我现在在这里....回答编辑以显示方法 – repzero

使用open()创建一个file object,写信给它,然后关闭它。

file = open("path/to/file.txt", "w+") 
for row in r:   
    file.write(row) 
file.close() 
+0

感谢分享! –

我喜欢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') 
+0

嗨我能够运行脚本。你能帮助理解过程,代码的每一行吗? –

+0

您有关于如何将每行打印到单独文件(txt)的提示 –

从其他的答案不同,你其实可以“打印”直接到文件相同的关键字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) 
+0

感谢您的分享! –