Python has a package that reads and writes a CSV file, which is directly import CSV. This Python package makes it easy to work with CSV files, some of which are simple to use.
1. Read the file
Csv_reader = Csv.reader (open (' Data.file ', encoding= ' Utf-8 ')) for row in Csv_reader: print (ROW)
For example, the following file
The output is as follows
[' 0.093700 ', ' 0.139771 ', ' 0.062774 ', ' 0.007698 ']
['-0.022711 ', '-0.050504 ', '-0.035691 ', '-0.065434 ']
['-0.090407 ', ' 0.021198 ', ' 0.208712 ', ' 0.102752 ']
['-0.085235 ', ' 0.009540 ', '-0.013228 ', ' 0.094063 ']
Visible Csv_reader each row of data into a list, each element in the list is a string .
2. Writing files
When reading a file, we read the CSV file into the list and write the file to the CSV file.
list = [' 1 ', ' 2 ', ' 3 ', ' 4 ']
out = open (outfile, ' w ') Csv_writer = Csv.writer (out) Csv_writer.writerow (list)
Possible problems: Using this notation directly will result in one more blank line after each line of the file.
The solution is as follows:
out = open (outfile, ' W ', newline= ") Csv_writer = Csv.writer (out, dialect= ' Excel ') Csv_writer.writerow (list)
Refer to the following:
In the StackOverflow found a more classical explanation, the original python3 inside the str and bytes type made a strict distinction, not like python2 inside some functions can be mixed. So when using Python3 to write Wirterow, open the file do not use WB mode, only need to use W mode, and then take newline= ".
3down vote |
In Python 2.X, it is required to open the csvfile with a ' B ' because the CSV module does its own line termination handling. In Python 3.X, the CSV module still does it own line termination handling, but still needs to know a encoding for unicod E strings. The correct-to-open a CSV file for writing is: outputfile=open("out.csv",‘w‘,encoding=‘utf8‘,newline=‘‘)
encoding Can is whatever require, but newline=‘‘ suppresses text mode newline handling. On Windows, failing to does this would write \r\r\n file line endings instead of the correct \ r \ n. This was mentioned in the 3.X Csv.reader documentation only, but Csv.writer requires it as well.
|
Links: http://blog.csdn.net/lixiang0522/article/details/7755059
Python3 reading a CSV file