Home Backend Development Python Tutorial How to implement file modification operation in Python? (with examples)

How to implement file modification operation in Python? (with examples)

Oct 09, 2018 pm 04:41 PM
python

The content of this article is about how to modify files under Python? (With examples), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Today we will discuss how to implement the operations of opening a file-modifying a file-closing a file in Python

This article adopts a line-by-line explanation method.

Idea:

Step one: Read the file
Part two: Use 'w' mode to write to a new file
Part 3: Delete the original file and rename the new file back to the original file
This completes the file modification operation

Let’s first take a look at the content of the original file

with open('xiakexing') as old_file:
    print(old_file.read())
Copy after login
Copy after login
赵客缦胡缨,吴钩霜雪明。银鞍照白马,飒沓如流星。
十步杀一人,千里不留行。事了拂衣去,深藏身与名。
闲过信陵饮,脱剑膝前横。将炙啖朱亥,持觞劝侯嬴。
三杯吐然诺,五岳倒为轻。眼花耳热后,意气素霓生。
救赵挥金锤,邯郸先震惊。千秋二壮士,烜赫大梁城。
纵死侠骨香,不惭世上英。谁能书阁下,白首太玄经。
Copy after login

The modification we want to make is to change the line "Thousands of Miles Not Leaving" in the second line to "Thousands of Miles Not Popular"
Additional explanation: Two files can be opened at the same time using the with open() format. In this case, it is actually opened file xakexing, and create the file xakexing.bak, and create the corresponding file objects old_file and new_file respectively

with open('xiakexing') as old_file,open('xiakexing.bak','w') as new_file:
#采用for循环从文件对象old_file里迭代地读取文件,简单来讲就是一行一行地读取文件,这样内存中只存储了一行文件的内容,节省了内存,也防止文件过大时造成的“超载”
    for i in old_file:
        if '千里不留行' in i: #这里每读取一行我们就对其进行条件判断,判断该行是否是我们要找的那一行
            i = i.replace('千','万')#当找到该行时,把该行的内容替换成我们想要的内容
#每读取一行我们就在新文件中写入一行,不管该行有没有变化,总之就是读一行、写一行、读一行、写一行
        new_file.write(i) 
#当for循环结束后,文件也已经被我们修改完毕了,这时应该删除旧文件,重命名新文件,为了实现这一目的,我们引入了os模块,os模块内主要是一些和操作系统有关的函数
import os            
os.remove('xiakexing') #删除原文件
os.rename('xiakexing.bak','xiakexing') #把新文件重命名回原文件名,最终实现了文件的修改
Copy after login

Then let’s take a look at the content of the file

with open('xiakexing') as old_file:
    print(old_file.read())
Copy after login
Copy after login
赵客缦胡缨,吴钩霜雪明。银鞍照白马,飒沓如流星。
十步杀一人,万里不留行。事了拂衣去,深藏身与名。
闲过信陵饮,脱剑膝前横。将炙啖朱亥,持觞劝侯嬴。
三杯吐然诺,五岳倒为轻。眼花耳热后,意气素霓生。
救赵挥金锤,邯郸先震惊。千秋二壮士,烜赫大梁城。
纵死侠骨香,不惭世上英。谁能书阁下,白首太玄经。
Copy after login

In this way, we have implemented the modification of the file . Since we are using the method with open() as, there is no need to close the file. If the file is opened with file=open(), a statement to close the file must be added at the end.

The above is the detailed content of How to implement file modification operation in Python? (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles