Loading...

Python文件读取和写入方法

读取

# 通过单字符串空格分隔
def count_words(filepath):
    with open(filepath, 'r') as file:
        string = file.read()
        string_list = string.split(" ")
        return len(string_list)
print(count_words("test.txt"))

# 通过多字符串逗号和空格分隔
import re
def count_words(filepath):
    with open(filepath, 'r') as file:
        string = file.read()
        string_list = re.split(r",| ", string)
        return len(string_list)
print(count_words("test.txt"))

写入

# 将26个小写英文字母写入文件
import string

with open("p001.txt", "w") as file:
    for letter in string.ascii_lowercase:
        file.write(letter + "\n")
posted @ 2023-08-24 14:49  高宏宇  阅读(13)  评论(0编辑  收藏  举报