The effect of this method is equivalent to that of ','
Division csv Formatted data , And store the segmented data in the list , It also removes the space at the end of the data generated by the final segmentation of each row 、 A newline 、 Tabs and so on .
import csv
with open('data.csv',mode='r',encoding='utf-8-sig',newline='') as File:
# Use csv.reader() Read each line of data in the file into a list
reader = csv.reader(File, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL)
# Traverse the list to output data in rows
for row in reader:
print(row)
Directly through Indexes To access the column elements of each row of data
for row in reader:
print(row[0])
csv.DictReader()
This method saves each line of data in the file in OrderedDict in , This data type is similar to a list nested with tuples , The first element in each tuple is the key , The second element is the value , The key in the tuple comes from CSV Header information in data .
import csv
results = []
with open('data.csv',mode='r',encoding='utf-8-sig',newline='') as File:
reader = csv.DictReader(File)
for row in reader:
print(row)
Read some information through key value
for row in reader:
print(row['MakeSpan'],row['WaitTime'])
About DictReader() More content of has not been learned yet , Please refer to other articles if necessary :CSV.DictReader() Method
import csv
Use open() Function to open a file ,open() Common parameters of functions :
file: File path 、 file name
mode: Turn on mode ,r( read-only ),w( Just write ),a( Append mode )
newline: Whether there is an empty line between each line , There are blank lines by default ,' '
: There is no vacancy .
myFile = open('example2.csv', 'w', newline='')
csv.writer modular , Used to write data to CSV:
csvfile: this can It's with write()
Method .
dialect=‘excel’: An optional parameter , Used to define specific CSV A set of parameters for .
fmtparam: Optional parameters , Can be used to overwrite existing formatting parameters .
writer = csv.writer(myFile)
Use writerow() and writerows() Writes data to CSV In file :
writerow(): Save the data to csv In a line in the file , Each element occupies one cell
writerows(): Save each list in the data to CSV In a line in the file , Each element in the list occupies one cell
myData1 = [[" this ", " yes ", "writerow", " Of ", " effect ", " fruit "],
[" this ", " yes ", "writerow", " Of ", " effect ", " fruit "],
[" this ", " yes ", "writerow", " Of ", " effect ", " fruit "]]
myData2 = [[" this ", " yes ", "writerows", " Of ", " effect ", " fruit "],
[" this ", " yes ", "writerows", " Of ", " effect ", " fruit "],
[" this ", " yes ", "writerows", " Of ", " effect ", " fruit "]]
myFile = open('example2.csv', 'w', newline='')
with myFile:
writer = csv.writer(myFile)
writer.writerow(myData1)
writer.writerows(myData2)
The effect of writing a file is as follows :