search

File operations in Python

Feb 27, 2017 pm 05:02 PM

1. The objects that can call methods must be objects, such as values, strings, lists, tuples, dictionaries, and even files. Everything in Python is an object.

 str1 = 'hello'
 str2 = 'world'
 str3 = ' '.join([str1,str2])
 print(str3)

2. Three basic file operation modes: r (only-read), w (only-write), a (append)

The process of operating files:

First, create a file object.

Second, call the file method to operate.

Third, don’t forget to close the file. (If the file is not closed, the content will be placed in the cache. Although Python will automatically read the content to the disk at the end, just in case, you must develop the habit of closing the file)

File file1

一张褪色的照片,
好像带给我一点点怀念。
巷尾老爷爷卖的热汤面,
味道弥漫过旧旧的后院;
流浪猫睡熟在摇晃秋千,
夕阳照了一遍他咪着眼;
那张同桌寄的明信片,
安静的躺在课桌的里面。

(1)r mode

Writing content in read-only mode will report an error.

 f = open('file1','r')
 f_read = f.read()   #read是逐字符地读取,read可以指定参数,设定需要读取多少字符,无论一个英文字母还是一个汉字都是一个字符。
 print(f_read)
 f.close()

 f = open('file1','r')
 f_read = f.readline() #readline只能读取第一行代码,原理是读取到第一个换行符就停止。
 print(f_read)
 f.close()

 f = open('file1','r')
 f_read = f.readlines() #readlines会把内容以列表的形式输出。
 print(f_read)
 f.close()

 f = open('file1','r')
 for line in f.readlines() #使用for循环可以把内容按字符串输出。
   print(line) #输出一行内容输出一个空行,一行内容一行空格... 因为文件中每行内容后面都有一个换行符,而且print()语句本身就可以换行,如果不想输出空行,就需要使用下面的语句:print(line.strip())
 f.close()

(2)w mode

All contents in the file will be cleared before operation. For example, if you write 'hello world' in file1, after the program is executed, there will be only the sentence 'hello world' in file1

 f = open('file1','w',encoding='utf8')  #由于Python3的默认编码方式是Unicode,所以在写入文件的时候需要调用utf8,以utf8的方式保存,这时pycharm(默认编码方式是utf8)才能正确读取,当读取文件时,文件是utf8格式,pycharm也是utf8,就不需要调用了。
 f_w = f.write('hello world')
 print(f_w)  #有意思的是,这里并不打印'hello world',只打印写入多少字符
 f.close()

(3)a mode

Different from w mode, a mode does not clear the original content, but moves the cursor to the last position of the content and continues to write new content. For example, append 'hello world'

 f = open('file1','a')
 f_a = f.write('hello world')
 print(f_a) #还是会打印写入的字符数
 f.close()

at the end to print the file, and append 'helloworld' after 'stray cat sleeping soundly on the swing' to output

In r mode, we said that we use for loop and readlines() to output the file content. The principle of this output content is: open the file, read the entire content into the memory, and then print the input. When the file is large , this reading method is unreliable and may even cause the machine to crash. We need to close the file in time, as follows:

f = open('file','r')
data=f.readlines()  #注意及时关闭文件
f.close()

num = 0
for i in data:
  num += 1
  if num == 5:
    i = ''.join([i.strip(),'hello world']) #不要使用“+”进行拼接
  print(i.strip())
f.close()

For big data files, use the following method:

num = 0
f.close()  #不要过早关闭文件,否则程序不能识别操作句柄f.
f = open('file','r')
for i in f:  #for内部把f变为一个迭代器,用一行取一行。
  num += 1
  if num == 5:
    i = ''.join([i.strip(),'hello world'])
  print(i.strip())
f.close()

3.tell and seek

tell: query the cursor position in the file

seek: cursor positioning

f = open('file','r')
print(f.tell())  #光标默认在起始位置
f.seek(10)    #把光标定位到第10个字符之后
print(f.tell())  #输出10
f.close()
----------------------
f = open('file','w')
print(f.tell())  #先清空内容,光标回到0位置
f.seek(10)    
print(f.tell())
f.close()
----------------------
f = open('file','a')
print(f.tell())  #光标默认在最后位置
f.write('你好 世界')
print(f.tell())  #光标向后9个字符,仍在最后位置
f.close()

4.flush synchronously transfers data from cache to disk

Example to implement progress bar function

import sys,time  #导入sys和time模块
for i in range(40):
  sys.stdout.write('*')
  sys.stdout.flush()  #flush的作用相当于照相,拍一张冲洗一张
  time.sleep(0.2)
下面代码也能够实现相同的功能
import time 
for i in range(40):
  print('*',end='',flush=True) #print中的flush参数
  time.sleep(0.2)

5.truncate truncation

Cannot be executed in r mode. In

w mode, all data has been cleared. Using truncate has no meaning. In

a mode, the content after the specified position is truncated. .

 f = open('file','a')
 f.truncate(6) #只显示6个字节的内容(6个英文字符或三个汉字),后面的内容被清空。

6. Summary of cursor position

A Chinese character has two bytes, and there are four methods involving the cursor position: read, tell, seek, truncate.

#--------------------------光标总结head-----------------------------------
f = open('file','r')
print(f.read(6)) #6个字符
print(f.tell())  #位置12字节,一个汉字两个字节
f.close()

f = open('file','r')
f.seek(6)      #6个字节
print(f.tell())
f.close()

f = open('file','a')
print(f.tell())  #光标默认在最后位置
f.write('你好 世界')
print(f.tell())  #光标向后9个字节,一个汉字两个字节,仍在最后位置 182-->191
f.close()

f = open('file','a',encoding='utf-8')
print(f.truncate(6)) #由于需要光标定位位置,所以也是字节。只显示6个字节的内容(6个英文字母或三个汉字,一个汉字两个字节),后面的内容被清空。
f.close()
#-----------------------------光标总结end---------------------------------

7. The other 3 modes: r+, w+, a+

r+: read and write mode, the cursor is at the starting position by default. When writing is needed, the cursor automatically moves to the end

w+: Write and read mode, first clear the original content, then write, you can also read

a+: Append reading mode, cursor The default is the last position, which can be written directly and can also be read.

f = open('file','a')
print(f.tell())  #末尾207位置
f.close()

f = open('file','r+')
print(f.tell())  #0位置
print(f.readline()) #读取第一行
f.write('羊小羚')   #光标移到末尾207位置并写入
print(f.tell())  #213位置
f.seek(0)     #光标移到0位置
print(f.readline())  #读取第一行
f.close()

8. Modify the file content

Idea: Due to the data storage mechanism, we can only read the contents of file 1 Come out, modify it, and put it in file 2.

f2 = open('file2','w',encoding='utf8')  #写入的时候必须加utf8
f1 = open('file','r')
num = 0
for line in f1: #迭代器
  num += 1
  if num == 5:
    line = ''.join([line.strip(),'羊小羚\n'])  #里面就是对字符串进行操作了
  f2.write(line)
f1.close()
f2.close()

9.with statement

can operate on multiple files at the same time. When the with code block is executed, the file will be automatically closed. To release memory resources, there is no need to specifically add f.close(). We will experience the usage and benefits of with through the following example.

Rewrite the code in 8 using the with statement


num = 0
with open('file','r') as f1,open('file2','w',encoding='utf8') as f2:
  for line in f1:
    num += 1
    if num == 5:
      line = ''.join([line.strip(),'羊小羚'])
    f2.write(line)

10. Summary

The above is the entire content of this article, I hope it can be helpful to everyone. If you have any questions, you can leave a message and communicate

For more articles related to file operations in Python, please pay attention to the PHP Chinese website!


Statement
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
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.