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!
-
2Just use 'open' to open a file and write itandria_girl– andria_girl2017年03月17日 17:05:25 +00:00Commented Mar 17, 2017 at 17:05
-
What format do you want it to be written inandria_girl– andria_girl2017年03月17日 17:07:55 +00:00Commented Mar 17, 2017 at 17:07
4 Answers 4
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")
6 Comments
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')
2 Comments
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()
1 Comment
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)