python Read and Write csv File Instance Code
- 2021-07-09 08:55:53
- OfStack
Python reading and writing CSV files requires importing CSV module of Python, and then reading and writing CSV files through functions csv. reader () and csv. writer () in CSV module.
Write to an CSV file
import csv # Need import csv File package of
out=open("aa.csv",'wb') # Note that if you use ' w' Open in the form, and there will be more data in the middle every time you write it 1 A blank line, so use ' wb'
csv_write=csv.write(out,dialect='excel')
# Let's write the specific content below
ss=['a',3]
csv_write.writerow(ss) # In this way ss The information inside is written to the aa.csv File, and it is in two columns
# Here, if you need to write more than one line, you can use a loop for loop input
out.close()
Read the CSV file
import csv
out=open("aa.csv",'r')
read_csv=csv.reader(out,dialect='excel')
for line in read_csv: # Cyclic output csv All data in the
print line
out.close()
Extension of knowledge points:
import csv
Read a file
reader method
with open('./data.csv', 'r') as f:
reader = csv.reader(f)
# python 2
header = reader.next()
# python 3x Use python Built-in next
header = next(reader)
# Get the real data
for row in reader:
print(row) # Print every 1 Row, list type, indexed only by position
A brief introduction to the next (iterable, [default]) function, which is a built-in python3x method for traversing iterative objects, where iterable can make strings, lists, dictionaries, ancestors, collections, etc. If default is given, this value is returned at the end of traversal, otherwise, an exception is thrown.
This reminds me of the dictionary's get () method, which has a similar effect. For example,
# If dic There is no inside key1 This key, then we return the specified 0
dic.get('key1', 0)
DictReader method
Write a file
Corresponding to reading, there are also two methods for writing
writer method, list of applicable lists
with open('./data.csv', 'w') as f:
header = ['col1', 'col2', ...]
writer = csv.writer(f)
writer.writeheader(header)
for row in row_list:
writer.writerow(row)
# Or call directly
writer.writerows(row_list)
DictWriter method, applicable dictionary list
with open('./data.csv', 'w') as f:
dictwriter = csv.DictWriter(f)
dictwriter.writeheader(dic_list[0].keys())
for dic in dic_list:
writer.writerow(dic)
# Or 1 Secondary write, call directly
wrier.writerows(dic_list)
They are all basic operations, so record 1 here. If you find it helpful, so much the better.