In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use csv module in Python". In daily operation, I believe many people have doubts about how to use 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 use csv module in Python". Next, please follow the editor to study!
1. Introduction to csv
CSV (Comma Separated Values), that is, comma-separated values (also known as character-separated values, because delimiters can not be commas), is a common type of text
Format for storing tabular data, including numbers or characters. Many programs will encounter files in the format of csv when dealing with data, which is more efficient than
More widely (the data provided by some topics on Kaggle are in csv format). Although csv is widely used, it does not have a common standard, so it is dealing with csv.
There is often trouble with the format, but fortunately python has a built-in csv module. Here is a brief introduction to some of the most commonly used functions in the csv module.
2. Functions in csv module
Reader (csvfile, dialect= "excel", * * fmtparams)
Parameter description:
Csvfile, which must be an Iterator-enabled object, can be a file object or a list object, if it is a file pair
For example, you need to add the "b" flag parameter when you open it.
Dialect, coding style, defaults to excel style, that is, separated by commas (,), dialect also supports customization, and registers by calling the register_dialect method, which will be mentioned below.
Fmtparam, the formatting parameter, is used to override the encoding style specified by the previous dialect object.
Import csvwith open ("test.csv", "rb") as myFile: lines=csv.reader (myFile) for line in lines: print line
"test.csv" is the file name, and the r in "rb" indicates "read" mode. Because it is a file object, add'b ". Open () returns a file object
MyFile,reader (myFile) only passes in the first parameter, and the other two parameters take the default value, which is read in excel style. Reader () returns a
The reader object lines,lines is a list, and when its method lines.next () is called, a string is returned. The effect of the above program is to change csv
The text in the file is printed on lines, and the elements of each line are separated by the comma separator ",".
In my test.csv file, the stored data is shown in the figure:
Program output:
["1", "2"]
["3", "a"]
["4", "b"]
Add: the reader object also provides some methods: line_num, dialect, next ()
Writer (csvfile, dialect= "excel", * * fmtparams)
The meaning of the parameter is the same as above. I will not repeat it here, but go directly to the routine:
With open ("t.csv", "wb") as myFile: myWriter=csv.writer (myFile) myWriter.writerow ([7, "g"]) myWriter.writerow ([8, "h"]) myList= [[1meme 2m 3], [4m 5m 6]] myWriter.writerows (myList)
"w" indicates the write mode.
First, the open () function opens the file named "t.csv" in the current path, and if it doesn't exist, it creates it and returns the myFile file object.
Csv.writer (myFile) returns the writer object myWriter.
The writerow () method writes one line, and the writerows method writes more than one line at a time.
Note: if the file "t.csv" exists in advance, calling the writer function will empty the text in the original file before executing the writerow/writerows method.
Add: in addition to writerow, writerows,writer objects also provide some other methods: writeheader, dialect
Register_dialect (name, [dialect,] * * fmtparams)
This function is used to customize dialect.
Parameter description:
Name, the name of your custom dialect. For example, the default is "excel". You can define it as "mydialect".
[dialect,] * * fmtparams,dialect format parameter, including delimiter (delimiter, default is comma), quotechar,
Quoting and so on, you can refer to Dialects and Formatting Parameters
Csv.register_dialect ("mydialect", delimiter= "|", quoting=csv.QUOTE_ALL)
The above one-line program customizes a dialect named mydialect, with only two parameters set for delimiter and quoting, and the others still use
The default value, where "|" is the delimiter. Then we can use "mydialect" as if we were using "excel". Let's see how it works:
Store the following data in my test.csv:
Print in "mydialect" style:
With open ("test.csv", "rb") as myFile: lines=csv.reader (myFile, "mydialect") print lines.line_num for line in lines: print line
Output:
["1jue 2", "3"]
["4jue 5", "6"]
As you can see, with "|" as the delimiter, 1 and 2 combine a string (because the delimiter between 1 and 2 is a comma, while the mydialect-style delimiter
The symbol is "|"), 3 a separate string.
For the writer () function, you can also pass in mydialect as an argument, which is not discussed here.
Unregister_dialect (name)
This function is used to log out the custom dialect
In addition, the csv module also provides get_dialect (name), list_dialects (), field_size_limit ([new_limit]) and other functions, all of which are compared.
It's easy. You can try it yourself. For example, the list_dialects () function lists all the dialect in the current csv module:
Print csv.list_dialects ()
Output:
["excel-tab", "excel", "mydialect"]
"mydialect" is customized. "excel-tab" and "excel" are built-in dialect, in which "excel-tab" is similar to "excel".
It's just that it takes tab as the delimiter.
The csv module also defines the
Some classes: DictReader, DictWriter, Dialect, etc., DictReader and DictWriter are similar to reader and writer.
Some constants: QUOTE_ALL, QUOTE_MINIMAL, .Quote _ NONNUMERIC, and so on, which can be used as values of Dialects and Formatting Parameters.
At this point, the study on "how to use the 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: 300
*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.