On the related operations python files and folders

File Operations

Opening and closing the file

  • Open the file
    using the Open (file name, access mode) function, you can open an existing file, or create a new file.
    Examples are as follows:
f = open('test.txt') # 访问方式可以省略,默认以r(只读)的形式
f = open('test.txt', 'w')
f = open('test.txt', 'w', encoding="utf-8")

encoding using the same operating system and the default encoding, window is gbk, linux is utf-8. Some of the window ide encoded as utf-8, at the time of operating files require additional setup = encoding "UTF-8"
| access method | Description |
| - | - |
| r | open read-only text file . Pointer file will be placed at the beginning of the file. This is the default mode. |
| W | open a text file for writing only. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
| A | open a text file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
To manipulate binary files (pictures, videos, and other non-text files), then behind the increase in b can be, for example, rb, wb, ab .
If the order of the file and read and write, is added at the + sign, e.g. r +, w +, a + , rb +, wb +, ab +.

  • Close the file
    close () method to close an open file.
    Examples are as follows:
f.close()

After the file is closed can not read and write, otherwise it will trigger ValueError errors.

Read and write files

  • Write data
    using the write () to write data to a file can be done
    when the file is opened in a text file, write (str) parameter is passed str (string type)
    when a file is opened in binary file, write (bytes) Incoming the parameters bytes (binary type)
# 以文本文件打开
f = open('test.txt', 'w', encoding="utf-8")
f.write('hello world, i am here!')
f.close()

# 以二进制文件打开
f = open('test.txt', 'wb')
f.write('hello world, i am here!'.encode("utf-8"))
f.close()
  • Read data (Read)
    using read (num) can read data from a file, NUM represents the length of the data read from the file (in bytes), if no incoming num, it means that the file is read All
    examples are as follows:
f = open('test.txt')

content = f.read(5)

print(content)

print("-"*30)

content = f.read()

print(content)

f.close()

"""
输出结果:
hello
------------------------------
 world, i am here!
"""

Note: If you read a number of data, then the data is read back from the position after the start of the last reading

  • Read data (the readline)
    the readline () method for reading a file from the entire line, including "\ n" characters. If a non-negative parameter specifies the number of bytes specified size are returned, including "\ n" characters.
    Test.txt file contents are as follows:

1: www.runoob.com
2: www.runoob.com
3: www.runoob.com
4: www.runoob.com
5: www.runoob.com

Examples are as follows:

f = open('test.txt', 'r')

content = f.readline()

print(content)

print("-"*30)

content = f.readline()

print(content)

f.close()

"""
输出结果:
1:www.runoob.com

------------------------------
2:www.runoob.com
"""
  • Read data (the readlines)
    as read when no argument, the readlines entire contents of file can be read in one time line manner, and returns a list, where each data row as an element.
    Examples are as follows:
f = open('test.txt', 'r')

content = f.readlines()

print(content)

f.close()
"""
输出结果:
['1:www.runoob.com\n', '2:www.runoob.com\n', '3:www.runoob.com\n', '4:www.runoob.com\n', '5:www.runoob.com']
"""

Positioning the read and write files

  • Get the current position of the read and write
    in the process of reading and writing files, if you want to know the current location, you can use tell () to get the
    file test.txt are as follows:

1: www.runoob.com
2: www.runoob.com
3: www.runoob.com
4: www.runoob.com
5: www.runoob.com

f = open("test.txt", "r")
str = f.read(3)
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

str = f.read(3)
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

f.close()
"""
读取的数据是 :  1:w
当前文件位置 :  3
读取的数据是 :  ww.
当前文件位置 :  6
"""

Note: The file position starts counting from 0

  • A target position
    if required to operate from a different position in the process of writing the document, you can use Seek ()
    Seek (offset, from) has two parameters
    • offset: Offset
    • from: direction
      • 0: beginning of the file
      • 1: indicates the current position
      • 2: end of file
f = open("test.txt", "r")
str = f.readline()
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

# 重新设置位置
f.seek(0, 0)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

str = f.readline()
print("读取的数据是 : ", str)

f.close()
"""
输出结果:
读取的数据是 :  1:www.runoob.com

当前文件位置 :  18
当前文件位置 :  0
读取的数据是 :  1:www.runoob.com
"""

Rename files, delete

Sometimes the need to file rename, delete, and so we had to use our module in Python os, os module provides a very rich way to handle files and directories.

  • Rename the file
    os module rename () can be done to the file rename operation.
    Syntax: rename (need to modify the file name, the new file name)
import os
# 将文件a重命名为文件b
os.rename("a.txt","b.txt")
  • Delete files
    os module remove () to complete the deletion of a file
    Syntax: remove (the file name to be deleted)
import os
os.remove("a.txt")

Folder Actions

The actual development, it is sometimes necessary to file with the way the program folder certain operations, such as create, delete, etc. as required to file operation os modules, if you want to operate the folder, the same need os module.

  • Create a folder
import os
os.mkdir("文件夹")
  • Get the current directory
import os
os.getcwd()
  • Change the default directory
# 表示跳到上一级目录
os.chdir("../")
  • Get a directory listing of the specified path
import os
# 不传入参数时,返回当前的路径的列表
os.listdir(path)
  • Delete the folder
import os
os.rmdir("文件夹")

Guess you like

Origin www.cnblogs.com/lxy0/p/11372534.html