I was bored and came across a post about reading and writing csv files. As a newbie in testing, I have always been fond of python. On a whim, I decided to play with it and share it with those who need it. Bai, for the python masters, it is simply childish. For a testing novice like me, seeing the code is like getting a shot of chicken blood. Well, good stuff, good stuff!
Writing of csv files: (Recommended learning: Python video tutorial)
stu1 = ['marry',26] stu2 = ['bob',23]
Writing The first step is also to open the file. Because we want to write, the mode we use is the 'a' mode to append content. As for "newline=", it means that because of the type of our csv file, if we do not add this , when we write something, a blank line will appear. You can try this without adding it, or you can "Old Turtle's Butt" (regulation)
out = open('Stu_csv.csv','a', newline='')
Let's define a variable below. Write, pass in the file variable just now, dialect is to define the type of the file, we define it as excel type
csv_write = csv.writer(out,dialect='excel')
and then write the data, blah blah blah, it is finally over, write The method is writerow. By writing the mode object, calling the method to write
csv_write.writerow(stu1) csv_write.writerow(stu2)
Finally, all newbies can use the syntax you are most familiar with to finish beautifully, 66666
print ("write over")
More For Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to write to csv in python. For more information, please follow other related articles on the PHP Chinese website!