In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the methods of dealing with Python files". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the Python file processing methods?"
1. Read-write file 1.1 read txt file (1) read all the contents in the file # Open the example.txt file and return the file object filewith open ('example.txt') as file:# read all the contents of the file through read () and store it as a string in all_contents all_contents = file.read () # display all contents print (all_contents)
After executing the program, output all the contents of the example.txt file:
Can't you see that the water of the Yellow River comes from the sky, and the waves rush to the East China Sea and never look back. Don't you see? sadly, the high hall mirror saw white hair, as black as green hair in the morning and as white as snow in the evening. Have fun when you are happy in life, and don't let the golden cup of jade show the sky to the bright moon. Heaven has made us talents, we're not made in vain. A thousand gold coins spent, more will turn up again. (2) read the contents of the file line by line. With open ('example.txt') as file:# traverses each line of for line in file:print (line) in the file
After executing the program, output each line in the example.txt file line by line:
Can't you see that the water of the Yellow River comes from the sky, and the waves rush to the East China Sea and never look back. Don't you see? sadly, the high hall mirror saw white hair, as black as green hair in the morning and as white as snow in the evening. Have fun when you are happy in life, and don't let the golden cup of jade show the sky to the bright moon. Heaven has made us talents, we're not made in vain. A thousand gold coins spent, more will turn up again.
It is easy to find that there is an extra blank line after each line is output. This is because there is an invisible newline character at the end of each line, and the print statement also adds a newline character, so there are two newline characters at the end of each line: one from the file and the other from the print statement. To eliminate these extra blank lines, use rstrip () in the print statement:
Print (line.rstrip ()) (3) create a list containing the contents of each line of the file
When the keyword with is used, the file object returned by open () is only available within the with code block. If you want to access the contents of a file outside the with code block, store the lines of the file in a list within the with code block and use the list outside the with code block: you can deal with the various parts of the file immediately, or you can postpone processing until later in the program.
The following example stores the lines of the file example.txt in a list in the with structure and prints them outside the with code block:
With open ("example.txt") as file:# reads each line from the file and stores it in a list lines lines = file.readlines () # print content line by line for line in lines:print (line.rstrip ())
After executing the program, output each line in the example.txt file line by line:
Can't you see that the water of the Yellow River comes from the sky, and the waves rush to the East China Sea and never look back. Don't you see? sadly, the high hall mirror saw white hair, as black as green hair in the morning and as white as snow in the evening. Have fun when you are happy in life, and don't let the golden cup of jade show the sky to the bright moon. Heaven has made us talents, we're not made in vain. A thousand gold coins spent, more will turn up again. 1.2 write txt file (1) write empty file
In the previous example, the open () we used actually contains two parameters:
The first parameter, filename. Indicates the name of a file that is open or written
The second parameter, mode. There are three modes: read mode ('r'), write mode ('w'), and additional mode ('a'). If you omit the mode argument, Python will open the file in the default read-only mode.
To write text to a file, you need to provide another argument when you call open ()-- the write mode ('w'), telling Python that you want to write to the open file. To understand how it works, let's store a simple message in a file:
# Open the file with open ("writeFile.txt", "w") as file:# write () in write mode and write a string to the file file.write ("I Love Python!")
After execution, you can find that a new file writeFile.txt has been generated in your project directory. The contents of this file are: I Love Python!
Note: Python can only write strings to text files. To store numeric data in a text file, you must first use the function str () to convert it to a string format.
(2) write multiple lines
The function write () does not add a newline character to the end of the text you write, so you can specify a newline character when writing:
# Open the file with open ("writeFile.txt", "w") as file:# write () in write mode and write a string to the file with a newline file.write ("I Love Python!\ n") file.write ("AI Jun Love Python too!\ n")
After execution, you can find that there are two lines in the generated new file writeFile.txt:
I Love Python!AI Jun Love Python too!
Note: if the writeFile.txt file already exists in the project directory, the newly written content will overwrite all the original contents.
(3) add new content to the file
If you want to add content to the file instead of overwriting the original content, you can open the file in additional mode. When you open a file in append mode, Python will not empty the file before returning the file object, and lines you write to the file will be added to the end of the file. If the specified file does not exist, Python will create an empty file for you.
Next, add some new content to the existing file writeFile.txt:
With open ("writeFile.txt", "a") as file:# adds file.write ("I Love Python beacause it can work well!") to the original writeFile.txt file.
After execution, a new line is added to the original content:
I Love Python!AI Jun Love Python too!I Love Python beacause it can work well! Second, store data
The module json allows you to dump a simple Python data structure into a file and load the data in the file when the program runs again. You can also use json to share data between Python programs. More importantly, the JSON data format is not specific to Python, which allows you to share data stored in JSON format with people using other programming languages. This is a lightweight format that is useful and easy to learn.
The JSON (JavaScript Object Notation) format was originally developed for JavaScript, but has since become a common format adopted by many languages, including Python.
2.1 write to json file
Use json.dump () to store the data in the JSON file:
# Import module jsonimport json# create a new list numbers = [1Jing 2Jing 3Jing 4Jing 5] # Open this file in write mode new.jsonwith open ("new.json", "w") as file:# uses json.dump () to store the list of numbers in the file json.dump (numbers, file)
After execution, a new file new.json is generated in the project directory, in which the newly added data is stored: [1, 2, 3, 4, 5]
Note: json is a built-in module in Python. When writing related programs, you can directly use import import without additional installation of the json library.
2.2 add content to the json file
Open the file in write mode, and the written content overwrites the contents of the original file. Sometimes when you want to add new content to the source file, you must open the file in append mode, as follows:
# Import module jsonimport json# create a new list list = [6, 7, 8, 9, 10] # Open this file in additional mode new.jsonwith open ("new.json", "a") as file:# uses json.dump () to store the list of numbers in the file json.dump (list, file)
After execution, the program adds new content to the original new.json file: [6, 7, 8, 9, 10]
2.3 read json files
Next, use the function json.load () to read the list in the JSON file into memory:
# Import module jsonimport json# opens this file in read-only mode new.jsonwith open ("new.json", "r") as file:# uses json.load () to read the contents of the JSON file into memory list = json.load (file) print ("the contents stored in the JSON file are:", list)
Running result:
The content stored in the JSON file is: [1, 2, 3, 4, 5] so far, I believe you have a deeper understanding of the "Python file processing methods", you might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.