遇到这样一个问题,比如我要处理一个文本文档,内容为
1
2
3
4
5
6
7
8
想让其变成3,4,5,6,7
就是取指定行,使用逗号代替空格,用shell很容易实现,xargs|sed -e就行,为啥Python实现这么费劲呢,请指教
望采纳,谢谢
test.txt文件:
# -*- coding = utf-8 -*-
# @time:2022/5/21 9:30
if __name__ == '__main__':
txt = ""
with open("test.txt","r") as fp:
txt = fp.read()
print(txt)
#空格代替
txt=txt.replace(" ",",")
print(txt)
效果:
一个with语句也能搞定:
with open("test.txt","r") as f:
print(','.join(f.read().split('\n')[2:7]))
#输出: 3,4,5,6,7