为了能到远方,脚下的每一步都不能少|

高宏宇

园龄:5年2个月粉丝:4关注:5

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")

本文作者:高宏宇

本文链接:https://www.cnblogs.com/gaohongyu/p/17654117.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   高宏宇  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起