


python basics_file operation method to achieve full text or single line replacement
This article mainly introduces the basics of python_file operations to achieve full-text or single-line replacement. It has a certain reference value. Now I share it with you. Friends in need can refer to it
Python modification file When using w mode, the original file will be cleared/overwritten. You can first open it with read (r), write it to the memory, and then open it with write (w).
1. Replace taste in the text with tasting
##
Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue
#将文件读取到内存中 with open("./fileread.txt","r",encoding="utf-8") as f: lines = f.readlines() #写的方式打开文件 with open("./fileread.txt","w",encoding="utf-8") as f_w: for line in lines: if "taste" in line: #替换 line = line.replace("taste","tasting") f_w.write(line)
2. Search and replace in the full text or replace in a single line
#文本内容 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue taste taste taste taste
#定义一个函数,带有4个参数 #x 表示要更新的文件名称 #y 表示要被替换的内容 #z 表示 替换后的内容 #s 默认参数为 1 表示只替换第一个匹配到的字符串 # 如果参数为 s = 'g' 则表示全文替换 def string_switch(x,y,z,s=1): with open(x, "r", encoding="utf-8") as f: #readlines以列表的形式将文件读出 lines = f.readlines() with open(x, "w", encoding="utf-8") as f_w: #定义一个数字,用来记录在读取文件时在列表中的位置 n = 0 #默认选项,只替换第一次匹配到的行中的字符串 if s == 1: for line in lines: if y in line: line = line.replace(y,z) f_w.write(line) n += 1 break f_w.write(line) n += 1 #将剩余的文本内容继续输出 for i in range(n,len(lines)): f_w.write(lines[i]) #全局匹配替换 elif s == 'g': for line in lines: if y in line: line = line.replace(y,z) f_w.write(line)
Test
1) Default parameter 1, only replace the first matched Line
string_switch("fileread.txt","taste","tasting") #结果 Yesterday when I was young 昨日当我年少轻狂 The tasting of life was sweet 生命的滋味是甜的 As rain upon my tongue taste taste taste taste
2) Global replacement
string_switch("fileread.txt","taste","tasting","g") #结果 Yesterday when I was young 昨日当我年少轻狂 The tasting of life was sweet 生命的滋味是甜的 As rain upon my tongue tasting tasting tasting tasting
The above is the detailed content of python basics_file operation method to achieve full text or single line replacement. For more information, please follow other related articles on the PHP Chinese website!

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools
