Python文本文件处理全解析
1. 文本文件内容递增处理
在处理文本文件时,有时需要对文件中的数值进行递增操作。下面的函数 increment_contents_both 可以实现这一功能,它能处理整数和浮点数:
def increment_contents_both(filename):
"""Increments values in a file, creating a new file.
Works with both ints and floats."""
data = open(filename, 'rt').readlines()
for i, line in enumerate(data):
for word in line.split():
try:
data[i] = line.replace(word, str(int(word)+1))
except ValueError:
try:
data[i] = line.replace(word, str(float(word)+1))
except ValueError:
# uncomment the following if you'd like feedback
# print(word, "is not a number")
超级会员免费看
订阅专栏 解锁全文
6374

被折叠的 条评论
为什么被折叠?



