In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to build csv module in python". In daily operation, I believe many people have doubts about how to build csv module in python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to build csv module in python". Next, please follow the editor to study!
What is a csv (Comma-Separated Values) file?
It is a file format, also known as a comma-separated value file, which can be opened using Excel software or text documents.
The data fields are separated by half-width commas (you can also use other characters), and when opened with Excel, the comma is converted to a delimiter.
Csv files store tabular data in plain text and are compatible with various operating systems.
For example, the following text exists in the form of a table in excel.
Sid,name,age
10010, Eraser, 18
10086, charming metonymy, 19
10000, bloggers, 20
The following is a simple explanation of the use of the python built-in module csv.
Clear solution of csv File in python to read File
Read the contents of the csv file using csv.reader ().
Import csv # module imports with open ('aa.csv',' ritual, newline='', encoding='utf-8') as f: # reader = csv.reader (f) for rin reader: print (r)
The prototype of the csv.reader () method is as follows:
Csv.reader (csvfile, dialect='excel', * * fmtparams)
The parameter csvfile can be any object, but requires that the object is an iterator, so both the file object and the list object can be passed in, and if it is a file object, it is required to open it with the parameter newline=''. The following parameters can be kept by default.
The second way is to use the DictReader class, which implements the same effect as the reader () method, and also receives an iterable object and returns the generator, the difference is that the returned result is put into the value of a dictionary, and the key of the dictionary is the title of the cell. And the function of this output is that there is no need to deal with the column header row of csv separately.
Import csv # module imports with open ('aa.csv',' ritual, newline='', encoding='utf-8') as f: reader = csv.DictReader (f) for rin reader: print (r)
Output:
OrderedDict ([('sid',' 10010'), ('name',' Eraser'), ('age',' 18')]) OrderedDict ([('sid',' 10086'), ('name',' charming Qiao Yu'), ('age',' 19')]) OrderedDict ([('sid',' 10000'), ('name',' bloggers'), ('age',' 20')]) write to the file
The module method used to write the csv file is csv.writer (). The prototype of this method is as follows:
Csv.writer (csvfile, dialect='excel', * * fmtparams)
The most basic write:
Import csvwith open ('abc.csv',' walled, newline='') as csvfile: W = csv.writer (csvfile) # write column header w.writerow (["sid", "name", "age"]) w.writerow (["10010", "eraser", "18"]) w.writerow (["10086", "hair charming metaphor", "18"])
At this point, if you open the file without newline='', after writing the contents of the csv file, there will be extra line breaks.
In addition, we can enable the dialect (dialect) parameter when we write to the csv file. For example, use | as the column delimiter.
The file writing code at this time is written as follows:
Class my_dialect (csv.Dialect): lineterminator ='\ r\ n' delimiter =' 'quotechar =' 'quoting = csv.QUOTE_MINIMALwith open (' abc.csv', 'walled, newline='') as csvfile: W = csv.writer (csvfile, dialect=my_dialect) # write column header w.writerow (["sid", "name", "age"]) w.writerow (["10010", "eraser", "18"]) w.writerow (["10086", "hair volume charming Qiao Yu") "18"])
The above code defines a new class, my_dialect, and causes it to inherit the csv.Dialect class, rewriting some of its fields.
Delimiter: delimiter. Default is
When the lineterminator:writer method writes data, the end character of each line defaults to\ r\ n
Quotechar: single character, used to wrap fields with special characters, such as delimiters, quotation mark characters, and newline characters. The default is "
Quoting: controls when writer generates quotation marks and when reader recognizes them. The default is QUOTE_MINIMAL, and the other values are
QUOTE_ALL (all in quotes)
QUOTE_MINIMAL (case-specific plus)
QUOTE_NONNUMERIC (all non-numeric additions)
QUOTE_NONE (none)
Description of the method for the Writer object:
Csvwriter.writerow (row): writing to a single line
Csvwriter.writerows (rows): writing multiple lines
Import csv # module imports csv_headers = ['name',' age'] rows = [('Eraser', 18), ('fascinating metaphor', 19), ('bloggers', 20)] with open ('. / aa.csv', 'winters, encoding='utf-8') Newline='') as f: csv_file = csv.writer (f) csv_file.writerow (csv_headers) # write header csv_file.writerows (rows)
Similar to the method used by the DictReader class, there is also a DictWriter class that will be written to the csv file field in field format.
Import csvwith open ('abc.csv',' name', newline='') as csvfile: W = csv.DictWriter (csvfile, fieldnames= ['sid',' name', 'age']) w.writeheader () # write column header w.writerow ({' sid': '10010,' name': 'eraser', 'age': 18}) w.writerow ({' sid': '10010,' name': 'eraser' 'age': 18}) w.writerow ({' sid': '10010', 'name':' Eraser', 'age': 18})
The above code pays particular attention to the fact that the fieldnames parameter is required, indicating the column header, and that you need to use w.writeheader () to write the column header before writing the official data.
Other instructions for csv files
With regard to the csv dialect, you can use the csv.register_dialect method to associate name with dialect, and the core meaning is equivalent to an alias for dialect. Deletion is also relatively simple, just use csv.unregister_dialect (name). Csv.list_dialects () returns the registered dialect name, and you can do a test on your computer to see several dialects available in the Python environment.
Import csvcsv.register_dialect ('ca', delimiter=' |', quoting=csv.QUOTE_MINIMAL) with open ('abc.csv',' name', newline='') as csvfile: W = csv.DictWriter (csvfile, fieldnames= ['sid',' name', 'age'], dialect='ca') w.writeheader () # write column header w.writerow ({' sid': '10010,' name': 'eraser' 'age': 18}) w.writerow ({' sid': '10010', 'name':' Eraser', 'age': 18}) w.writerow ({' sid': '10010', 'name':' Eraser', 'age': 18})
The csv module also provides the csv.Sniffer class, which is used to infer the format of the csv file, which has two methods:
Sniff (sample, delimiters=None): parses and returns a dialect subclass, which can parse out format parameters
Has_header (sample): analyzes whether a title exists in the csv file.
At this point, the study on "how to build csv module in python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.