Writing to a text file? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Writing to a text file? (/thread-13377.html) |
Writing to a text file? - Bigjay45 - Oct-11-2018 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] RE: Writing to a text file? - Larz60+ - Oct-12-2018 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. RE: Writing to a text file? - Bigjay45 - Oct-12-2018 (Oct-12-2018, 12:58 AM)Larz60+ Wrote: open a 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](Oct-12-2018, 01:25 AM)Bigjay45 Wrote:(Oct-12-2018, 12:58 AM)Larz60+ Wrote: open a text file: RE: Writing to a text file? - pcsailor - Oct-12-2018 Check these two links out for pin-pointed info: https://automatetheboringstuff.com/chapter14/ https://automatetheboringstuff.com/chapter8/ Hope that helps, Phil RE: Writing to a text file? - Larz60+ - Oct-12-2018 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() |