Python file processing open() function

File handling is an essential part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

file handling

The key function for working with files in Python is the  open()  function.

There are four different ways (modes) of opening files:

  • "r"  - read - default value. Open the file for reading, and report an error if the file does not exist.
  • "a"  - Append - Open the file for appending, or create the file if it does not exist.
  • "w"  - write - open the file for writing, or create the file if it doesn't exist.
  • "x"  - Create - Creates the specified file, returning an error if the file exists.

Additionally, you can specify whether the file should be processed as binary or text mode.

  • "t"  - text - default value. text mode.
  • "b"  - binary - binary mode (eg image).

The open() function takes two parameters: filename and mode. 

open() function syntax format:

f=open("a.txt","r")    #以只读的方式打开a.txt文件,并创建一个文件对象f。
这里的f等于以只读的方式打开的a.txt文件

In the read() function      , you can enter the number of characters in the file you want to read in the parentheses. If there are no parameters in the parentheses, the entire content of the file is read by default.

print(f.read())    #读取文件全部内容
print(f.read(6))    #读取文件前6个字符

The readline() function        reads the contents of a line of files

print(f.readline())    #读取第一行内容

#若只想读取前两行内容,则可以这样写:
print(f.readline())
print(f.readline()) 
   
"""依次读取一行内容,已经读取的内容不会重复读取,所以写两遍就可以读取两行内容。"""

The close() function       closes the file Since there is open() to open the file, there is close() to close the file

Write the contents of the buffer to the file, close the file at the same time, and release the resources related to the file object

After opening the file, close the file after editing and using the file

#close()函数使用方法:

f=open("a.txt","r")     #打开文件
print(f.read(5))        #读取前五个字符
print(f.readline())     #然后再读取一行字符
f.close()            #完成对文件的使用后关闭文件

Python file writing

write to existing file

To write to an existing file, you must add parameters to the open() function:

  • "a" - append - will append to the end of the file

  • "w" - write - will overwrite any existing content

Open the file "a.txt" and append the contents to the file

f=open("a.txt","a")    #以"a"追加写入的方式打开文件
f.write("Hello python!")   #以"a"的方式打开的文件写入内容时,会将内容追加在之前内容的末尾。
f.close()     #将缓冲区的内容写入到文件中,写完内容后关闭文件。

"""每次运行都会在文件末尾追加Hello python,运行三次后,就会有三句Hello python"""

Open the file "a.txt" and overwrite the content

f=open("a.txt","w")      #以"w"写入的方式打开a.txt文件
f.write("Hello python!")    
#以"w"方式打开的文件,每次写入内容都会覆盖之前的内容。所以不管运行多少次,文件里只有Hello python!
f.close()   #把缓冲区的内容写入文件,并关闭文件。释放文件对象的相关资源。
"""每次写入完内容后建议关闭一下文件,因为文件不一定会立马保存进文件,而是存在缓冲区。
使用close() 函数关闭文件时,会将缓冲区的内容写入文件。"""

Note: The "w" method overrides everything.

Create new file:

If you need to create a new file in python, use the open() method and use the following method:

"x" create - will create a file, return an error if the file exists

"a" append - will create a file if the specified file does not exist

"w" write - will create a file if the specified file does not exist

Example:

Create a file named "b.txt":

f=open("b.txt","x")       #创建并打开b.txt文件

#如果文件已存在则报错显示文件以存在:

FileExistsError: [Errno 17] File exists: '海龟编程test1.py'

#如果不存在,则创建新文件。

Delete Files

If you need to delete a file, you must import the OS module and run its os.remove() function:

#删除b.txt文件
import os    #导入os模块
os.remove("b.txt")     #使用os.remove("文件名") 函数删除文件。

Check if file exists

To avoid errors, you may want to check for the existence of a file before trying to delete it:

example

Check if the file exists, then delete it:

import os
if os.path.exists("d.txt"):
  os.remove("d.txt")
else:
  print("The file does not exist")

delete folder

To delete an entire folder, use the os.rmdir() method:

import os 
os rmdir("b.txt")     # 删除整个文件夹

Note: You can only delete empty folders

Guess you like

Origin blog.csdn.net/weixin_53466908/article/details/123494995