Python - operate txt files

create txt file


import os

file = os.getcwd()
if not os.path.exists(file + os.sep + "test666.txt"):
    os.mknod("test666.txt")

open txt file

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)The function is used to open the txt file.

#方法1,这种方式使用后需要关闭文件
f = open("data.txt","r", encoding='utf8')
f.close()
 
#方法2,使用文件后自动关闭文件
with open('data.txt',"r", encoding='utf8') as f:

Parameter Description:

  • file: file path (relative path or absolute path)
  • mode: the mode to open the file, commonly used are: r, w, a, r+, w+,a+
    • r: Open the file in read mode, and the file information can be read.
    • w: Open the file in write mode, you can write information to the file. If the file exists, clear the file and write new content.
    • a: Open the file in append mode (that is, once the file is opened, the file pointer will automatically move to the end of the file), if the file does not exist, it will be created.
    • r+: Open the file in read-write mode, and the file can be read and written.
    • w+: Erase the file content, then open the file for reading and writing.
    • a+: Open the file in read-write mode, and move the file pointer to the end of the file.
  • buffering: set buffering
  • encoding: common encoding: utf8GBK
  • errors: error level
  • newline: distinguish newline characters
  • closefd: the incoming file parameter type

read txt file

  • f.read(int count)Read the file, if there is count, read count characters, if not set count, read the entire file. The returned data type is str.
  • f.readline()Read a line of information. The returned data type is str.
  • f.readlines()Read all lines, that is, read the information of the entire file. The returned data type is list.

Example 1 :
shuyu

file_path = "read.txt"  # 文件位置,这里用的相对路径
with open(file_path, "r", encoding='utf8') as f:  # 获取文件对象,
    lines = f.readlines()   # 使用readlines()读取文件所有行
    for line in lines:      # 循环读出的所有行
        print(line, end='') # 输入每一行,并去掉原有的'/n',line.strip()也可以

Example 2: Convert a number to a list of strings
shuyu

file_path = "../test.txt"
with open(file_path, "r", encoding='utf8') as f:
    lines = f.readlines()
    for line in lines:
        # astr = "'" + line.replace(’\n’,’’) + "',"   # 去掉/n 方式一
        astr = "'" + line[:-1] + "',"                 # 去掉/n 方式二
        print(astr)

write to txt file

  • f.write(str)Write str string to file.
  • f.writelines(list)Write the strings in the list to the file line by line, which is written continuously to the file without line breaks.

Example 1 :
shuyu

file_path = "write.txt"
data_list = ["不登高山,不知天之高也;", "不临深溪,不知地之厚也。"]
with open(file_path, "w", encoding='utf8') as f:
    for line in data_list:
        f.write(line + '\n')

delete txt file

import os
os.remove(r"test.txt")  # 对所有类型的文件有效

Guess you like

Origin blog.csdn.net/weixin_44988085/article/details/129298128