Print python script to a file

Hi Im a newbie about python,

I have 2000 list of company that I want to share in my website. I was able to import my csv file, using python script. This is my code:

import csv

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

Will you help me on how can I print this to a file?

Thanks!

Upvotes: 0

Views: 139

Answers (4)

repzero
repzero

Reputation: 8412

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

Printing each row in separate files generated with an increment number

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

Upvotes: 1

Doyousketch2
Doyousketch2

Reputation: 2147

I like repzero's answer, but rows need to be converted to str()

import csv  ##  import comma separated value module

open test.csv in readonly mode as a variable csvfile

with open('test.csv', 'r') as csvfile:  

set the variable csvdata to all the data read from csvfile,
splitting everytime it finds a comma

    csvdata = csv.reader(csvfile, delimiter=',')  

open test.txt in write mode as a variable text_file

    with open(test.txt, 'w') as text_file:  

iterate through every row of the csv data

        for row in csvdata:  

convert the row of data into a string of text,
and write it to the file, followed by a newline

            text_file.write(str(row) + '\n')

Upvotes: 1

Taku
Taku

Reputation: 33714

Differ from the other answers, you can actually "print" directly to a file using the same keyword print. By rerouting the file method:

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)

Upvotes: 0

Avantol13
Avantol13

Reputation: 1059

Create a file object using open(), write to it, then close it.

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

Upvotes: 0

Related Questions