Python Forum

Full Version: Writing to a text file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import csv

with open('animals3.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
           
            print(row[0])
            print(row[1])
            print(row[2])
How do you write the results into a text file shown below
I have looked at different videos but cant figure it out
Thank you


[Image: 2w4h1fk.jpg]
open a text file:
with open('myfilename.txt', 'w') as fp:
    for row in rows:
        fp.write(row)
But the csv file is already a file, and can be used as any other text file.
(Oct-12-2018, 12:58 AM)Larz60+ Wrote: [ -> ]open a text file:
with open('myfilename.txt', 'w') as fp:
    for row in rows:
        fp.write(row)
But the csv file is already a file, and can be used as any other text file.

I typed this
import csv
 
with open('animals3.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
with open('myfilename.txt, 'w') as fp:
    for row in rows:
         fp.write(row)
Error I got:
NameError:name 'rows' is not defined

Error:
[error]
[/error]
(Oct-12-2018, 01:25 AM)Bigjay45 Wrote: [ -> ]
(Oct-12-2018, 12:58 AM)Larz60+ Wrote: [ -> ]open a text file:
with open('myfilename.txt', 'w') as fp:
    for row in rows:
        fp.write(row)
But the csv file is already a file, and can be used as any other text file.

I typed this
import csv
 
with open('animals3.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
with open('myfilename.txt, 'w') as fp:
    for row in rows:
         fp.write(row)
Error I got:
Error:
NameError:name 'rows' is not defined
Check these two links out for pin-pointed info:
https://automatetheboringstuff.com/chapter14/
https://automatetheboringstuff.com/chapter8/
Hope that helps,
Phil
It should be something like this (untested):
import csv
  
with open('animals3.csv') as csvfile, open('myfilename.txt, 'w') as fp:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
         fp.write(row)
Again this is rather pointless as a csv file is a text file!
you can read as:
with open('animals3.csv') as fp:
    for line in fp:
        print(line.strip()