current position:Home>A glance at Python's file processing (Part 1)
A glance at Python's file processing (Part 1)
2022-01-31 12:45:31 【Lei Xuewei】
「 This is my participation 11 The fourth of the yuegengwen challenge 10 God , Check out the activity details :2021 One last more challenge 」
ceremonial Python Column No 34 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !
A lot has been written before , Are doing some data processing , But when we need to store and read data , You need documents . The school committee took you through file processing .
First learn to read and write documents !
For example, when I was at school , The design requirement of the first programming course is to make a student management system .
This requires the use of files to handle ( You can also use a database , But in general C Language is the preferred language for many freshmen in computer department , At this time, the probability does not know the database ).
python The most common is open and write function , as follows :
#open function : Receive a file name , There are other parameters that can be omitted .
one_file = open('myfile.txt')
# Read data assigned to data Variable
data = one_file.read()
# Of a file object write function
one_file = open('myfile.txt','w')
#write function : Incoming data ,write Function writes data to one_file In the corresponding file .
one_file.write(' Data written to a file ')
Copy code
Let's take a look at some examples of file operations
Read file data
Keep the following data as a file :sample.txt
Continuous learning
Continuous development
My name is Lei Xuewei
Copy code
afile = open("sample.txt")
print(afile.read())
Copy code
Write data and simply display
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/12 11:58 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : filedemo.py
# @Project : hello
afile = open("sample.txt")
data = afile.read()
print("sample file content=", data)
afile.close()
# hold sample The read data is written to test file
afile = open("./test.txt", "w")
afile.write(data)
afile.close()
print("write data to test file!")
afile = open("./test.txt")
data = afile.read()
afile.close()
print("test file content=", data)
Copy code
Let's see , The read content is indeed written .
The operation of this file is very simple .
Reading and writing files is so simple , But after we manipulate the file , Remember to call close function ( Close file , Otherwise, exceptions will occur in subsequent read / write operations / error !)
close The function is called as follows :
one_file.close() # File object .close()
Copy code
But we usually write this style of file reading and writing :
with open('sample.txt', 'r') as one_file:
data = one_file.read()
# No need to call close 了 , This with Within code block ,python Will help us automatically close the file .
Copy code
All the above are read at one time as soon as you open the file ,Python You can also read line by line .
According to the line read / Write data by line
According to the line read
We modified the code based on the previous read-write file , Look directly at :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/12 11:58 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : filedemo2.py
# @Project : hello
with open("sample.txt") as afile:
data = afile.readline()
print("sample file content=", data)
with open("./test.txt", "w") as afile:
afile.write(data)
print("write data to test file!")
with open("test.txt") as afile:
data = afile.readline()
print("test file content=", data)
Copy code
We see here reading sample One line of the file , Then write to test file , There is only one line !
summary
Python The reading of files is very convenient , Built in open Functions and file objects come with write function , The design is very simple .
Open the box , So simply knock , Take a few minutes to learn some file operations !
by the way , like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column
Continuous learning and continuous development , I'm Lei Xuewei !
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !
copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311245299349.html
The sidebar is recommended
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
guess what you like
-
How IOS developers learn python programming 3-operator 2
-
How IOS developers learn python programming 2-operator 1
-
[Python applet] 8 lines of code to realize file de duplication
-
Python uses the pynvml tool to obtain the working status of GPU
-
Data mining: Python actual combat multi factor analysis
-
Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
-
Use Python VTK to batch read 2D slices and display 3D models
-
Complete image cutting using Python version VTK
-
Python interface automation test framework (basic) -- common data types Dict
-
Django (make an epidemic data report)
Random recommended
- Python specific text extraction in actual combat challenges the first step of efficient office
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert(python)
- leetcode 2062. Count Vowel Substrings of a String(python)
- Analysis of Matplotlib module of Python visualization
- Django permission management
- Python integrated programming -- visual hot search list and new epidemic situation map
- [Python data collection] scripy realizes picture download
- Python interface automation test framework (basic part) -- loop statement of process control for & while
- Daily python, Chapter 9, while loop
- Van * Python | save the crawled data with docx and PDF
- Five life saving Python tips
- Django frequency control
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence(python)
- leetcode 2027. Minimum Moves to Convert String(python)
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph(python)
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores(python)
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching