Use python to read multiple txt files in a folder


1. Read multiple txt files in a folder

Example: pandas is a tool based on NumPy that was created to solve data analysis tasks.

# 获取file_path路径下的所有TXT文本内容和文件名
def get_txts(file_path):
    files = os.listdir(file_path)
    txt_list = []
    for file in files:
        with open(os.path.join(file_path, file), "r", encoding="UTF-8") as f:
            txt_list.append(f.read())
    return txt_list, files

Where file_path is the folder name, obtain all the file name collection files under the folder through os.listdir(), then loop to read the text in each file, and return the text collection txt_list and the file name collection files.


2. Append to write txt

(1) Open txt file

file_write=open('文件名.txt',mode='a')

Commonly used modes for writing include:

  • a: Open a file for appending content. If the file exists, the file pointer points to the end. If the file does not exist, a new file is created for writing.
  • w: Open a file for writing. If the file exists, open the file and start editing from the beginning of the file, and the original content will be deleted. If the file does not exist, create a new file and write it.

(2) Write to file
Write a small amount of text string:

str="你好,世界"
file_write.write(str)

or
writes a large sequence of text strings:

list=["...","...","...",...]
file_write.writelines(list)

3. Read txt content

file_read=open('文件名.txt',mode='r',encoding="UTF-8")
file_txt=file_read.readlines()
file_txt
  • r: Open the file in read-only mode, and place the file pointer at the beginning of the file.

The brackets can be written as (‘file name.txt’, ‘r’, encoding="UTF-8"), and readlines() means reading all the contents line by line into the list, as follows:
Insert image description here


Summarize

The above are the notes about using python to read multiple txt files in a folder. I hope it will be helpful to you. The author is also learning. If there are any unclear or wrong explanations, please correct me. .

Guess you like

Origin blog.csdn.net/weixin_56242678/article/details/131410367