Home Backend Development Python Tutorial Detailed explanation of Python file operations

Detailed explanation of Python file operations

Sep 21, 2017 am 10:52 AM
python document Detailed explanation

This article mainly introduces the detailed explanation and examples of Python file operations. I hope that through this article, everyone can understand and master the knowledge of Python file operations. Friends in need can refer to

Python files Detailed explanation and examples of operations

1. File operations

1. File operation process

  • Open the file , get the file handle and assign it to a variable

  • Operation on the file through the handle

  • Close the file

The existing files are as follows:


昨夜寒蛩不住鸣。
惊回千里梦,已三更。
起来独自绕阶行。
人悄悄,帘外月胧明。
白首为功名,旧山松竹老,阻归程。
欲将心事付瑶琴。
知音少,弦断有谁听。

f = open('小重山') #打开文件
data=f.read()#获取文件内容
f.close() #关闭文件
Copy after login

Note: if in the win, the hello file is saved in utf8, and the open function is passed through the operating system when opening the file. Open the file, and the default encoding of the win operating system is gbk, so opening it directly will cause garbled characters. You need f=open('hello', encoding='utf8'). If the hello file is saved in gbk, you can open it directly.

2. File opening mode

Character Meaning


##

'r'    open for reading (default)
'w'    open for writing, truncating the file first
'x'    create a new file and open it for writing
'a'    open for writing, appending to the end of the file if it exists
'b'    binary mode
't'    text mode (default)
'+'    open a disk file for updating (reading and writing)
'U'    universal newline mode (deprecated)
Copy after login

First introduce the three most basic modes:


# f = open('小重山2','w') #打开文件
# f = open('小重山2','a') #打开文件
# f.write('莫等闲1\n')
# f.write('白了少年头2\n')
# f.write('空悲切!3')
Copy after login

3. Specific file operations


f = open('小重山') #打开文件
# data1=f.read()#获取文件内容
# data2=f.read()#获取文件内容
#
# print(data1)
# print('...',data2)
# data=f.read(5)#获取文件内容

# data=f.readline()
# data=f.readline()
# print(f.__iter__().__next__())
# for i in range(5):
#   print(f.readline())

# data=f.readlines()

# for line in f.readlines():
#   print(line)


# 问题来了:打印所有行,另外第3行后面加上:'end 3'
# for index,line in enumerate(f.readlines()):
#   if index==2:
#     line=''.join([line.strip(),'end 3'])
#   print(line.strip())

#切记:以后我们一定都用下面这种
# count=0
# for line in f:
#   if count==3:
#     line=''.join([line.strip(),'end 3'])
#   print(line.strip())
#   count+=1

# print(f.tell())
# print(f.readline())
# print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.
# print(f.read(5))#一个中文占三个字符
# print(f.tell())
# f.seek(0)
# print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符

#terminal上操作:
f = open('小重山2','w')
# f.write('hello \n')
# f.flush()
# f.write('world')

# 应用:进度条
# import time,sys
# for i in range(30):
#   sys.stdout.write("*")
#   # sys.stdout.flush()
#   time.sleep(0.1)

# f = open('小重山2','w')
# f.truncate()#全部截断
# f.truncate(5)#全部截断

# print(f.isatty())
# print(f.seekable())
# print(f.readable())

f.close() #关闭文件
Copy after login

Next we continue to expand the file mode :


# f = open('小重山2','w') #打开文件
# f = open('小重山2','a') #打开文件
# f.write('莫等闲1\n')
# f.write('白了少年头2\n')
# f.write('空悲切!3')


# f.close()

#r+,w+模式
# f = open('小重山2','r+') #以读写模式打开文件
# print(f.read(5))#可读
# f.write('hello')
# print('------')
# print(f.read())


# f = open('小重山2','w+') #以写读模式打开文件
# print(f.read(5))#什么都没有,因为先格式化了文本
# f.write('hello alex')
# print(f.read())#还是read不到
# f.seek(0)
# print(f.read())

#w+与a+的区别在于是否在开始覆盖整个文件


# ok,重点来了,我要给文本第三行后面加一行内容:'hello 岳飞!'
# 有同学说,前面不是做过修改了吗? 大哥,刚才是修改内容后print,现在是对文件进行修改!!!
# f = open('小重山2','r+') #以写读模式打开文件
# f.readline()
# f.readline()
# f.readline()
# print(f.tell())
# f.write('hello 岳飞')
# f.close()
# 和想的不一样,不管事!那涉及到文件修改怎么办呢?

# f_read = open('小重山','r') #以写读模式打开文件
# f_write = open('小重山_back','w') #以写读模式打开文件

# count=0
# for line in f_read:
  # if count==3:
  #   f_write.write('hello,岳飞\n')
  #
  # else:
  #   f_write.write(line)


  # another way:
  # if count==3:
  #
  #   line='hello,岳飞2\n'
  # f_write.write(line)
  # count+=1

# #二进制模式
# f = open('小重山2','wb') #以二进制的形式读文件
# # f = open('小重山2','wb') #以二进制的形式写文件
# f.write('hello alvin!'.encode())#b'hello alvin!'就是一个二进制格式的数据,只是为了观看,没有显示成010101的形式
Copy after login

Note 1: Whether it is py2 or py3, equal byte replacement can be done in r+ mode, but it does not make any sense!


Note 2: Some students will use readlines here to get the content list, then modify the corresponding content through the index, and finally rewrite the list into the file.

There is a big problem with this idea. If the data is very large, your memory will not be able to bear it. Our method can optimize this process through iterators.

Supplement: rb mode and seek

In py2:

##

#昨夜寒蛩不住鸣.

f = open('test','r',) #以写读模式打开文件

f.read(3)

# f.seek(3)
# print f.read(3) # 夜

# f.seek(3,1)
# print f.read(3) # 寒

# f.seek(-4,2)
# print f.read(3) # 鸣
Copy after login

In py3 :

# test: 
昨夜寒蛩不住鸣.

f = open('test','rb',) #以写读模式打开文件

f.read(3)

# f.seek(3)
# print(f.read(3)) # b'\xe5\xa4\x9c'

# f.seek(3,1)
# print(f.read(3)) # b'\xe5\xaf\x92'

# f.seek(-4,2)
# print(f.read(3))  # b'\xe9\xb8\xa3'

#总结: 在py3中,如果你想要字符数据,即用于观看的,则用r模式,这样我f.read到的数据是一个经过decode的
#   unicode数据; 但是如果这个数据我并不需要看,而只是用于传输,比如文件上传,那么我并不需要decode
#   直接传送bytes就好了,所以这个时候用rb模式.

#   在py3中,有一条严格的线区分着bytes和unicode,比如seek的用法,在py2和py3里都是一个个字节的seek,
#   但在py3里你就必须声明好了f的类型是rb,不允许再模糊.

#建议: 以后再读写文件的时候直接用rb模式,需要decode的时候仔显示地去解码.
Copy after login

4. With statement

In order to avoid forgetting to close the file after opening it, you can manage the context, that is:

with open('log','r') as f:
    pass
Copy after login

In this way, when the with code block is executed, the file resources will be automatically closed and released internally.

After Python 2.7, with supports managing the context of multiple files at the same time, that is:

with open('log1') as obj1, open('log2') as obj2:
  pass2
Copy after login

The above is the detailed content of Detailed explanation of Python file operations. 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)

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.

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.

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.

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.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles