1.需求
程序1: 实现简单的shell sed替换功能
file1 的内容copy到file2
输入参数./sed.py $1 $2
$1替换成$2 (把a替换成% )
2.个人思路
open file 1 2 file1 内容 copy 到 file2 read 每一行 , if a in line: a替换% 关闭file1 file2
代码
f1 = open('yes.txt','r+',encoding='utf-8')
f_new = open('yes2.txt','w',encoding='utf-8') for line in f1.readlines():
line = line.replace('a','%').strip()
print(line)
f_new.writelines(line) f1.close()
f_new.close()
3.个人心得
3.1 读取文件
方法1:记得f1.close() f_new.close()
f1 = open('yes.txt','r+',encoding='utf-8')
f_new = open('yes2.txt','w',encoding='utf-8')
方法2:自动帮你关闭文件
with open('yes.txt','r+',encoding='utf-8') as f1:
with open('yes2.txt','w',encoding='utf-8') as f_new: for line in f1.readlines():
3.2 copy全部
方法1:f1 的内容copy到f_new
#全文复制
f1 = open('yes.txt','r+',encoding='utf-8')
f2 = open('yes2.txt','w',encoding='utf-8')
for line in f1.readlines():
print(line.strip())
f_new.writelines(line) #此时光标已经到末尾了
方法2:shutil模块(文本处理,压缩)
import shutil
shutil.copyfile("yes.txt","yes2.txt")
3.3 文件替换
读取 f1 的每行,a替换成%,并且写入到f_new
f1 = open('yes.txt','r+',encoding='utf-8')
f2 = open('yes2.txt','w',encoding='utf-8') for line in f1.readlines():
line = line.replace('a','%').strip()
print(line)
f_new.writelines(line)
3.4 光标问题
注意:全文复制,(读取每一行,然后copy到 f2 ),此时光标已经到文件末尾! 执行替换时,已经读取不到内容
错误代码
# coding=utf-8 #打开文件
f1 = open('yes.txt','r+',encoding='utf-8')
f_new = open('yes2.txt','w',encoding='utf-8') #全文复制
for line in f1.readlines():
print(line.strip())
f_new.writelines(line) #光标已经到末尾了
a = f1.readlines() # a[] #替换
for line in f1.readlines():
line = line.replace("a",'%')
print(line.strip())
f_new.writelines(line)
3.5 sys模块 传入参数
传入参数 sys.argv[1]
import sys
#打开文件
with open('yes.txt','r+',encoding='utf-8') as f1:
with open('yes2.txt','w',encoding='utf-8') as f_new: find_str = sys.argv[1]
replace_str = sys.argv[2]
cmd 执行代码时,可以带参数
D:\PycharmProjects\s14\作业>python "3-1 shell sed功能2.1.py" a %
4. 完整代码
# coding=utf-8 import sys
#打开文件
with open('yes.txt','r+',encoding='utf-8') as f1:
with open('yes2.txt','w',encoding='utf-8') as f_new: find_str = sys.argv[1]
replace_str = sys.argv[2] #替换
for line in f1.readlines():
line = line.replace(find_str,replace_str).strip()
print(line)
f_new.writelines(line) f1.close()
f_new.close()