python - python - 如何用Python中另一个txt文件中的一行替换txt文件中的一行
问题描述
我有两个txt文件:
Dummy-dates.txt contains:
0/0/0000|
1/0/0000|
2/0/0000|
etc... up to 31.
single-dates.txt contains:
2/0/0000|Johns Bday
6/0/0000|Some other cool date
etc.. can have random number of lines within 1-31 in the start
I need to create a new txt file containing:
0/0/0000|
1/0/0000|
2/0/0000|Johns Bday
3/0/0000|
4/0/0000|
5/0/0000|
6/0/0000|Some other cool date
7/0/0000|
etc.... up to 31
我无法弄清楚 - 我尝试过使用嵌套的 for 循环。谁能帮我吗?
解决方案
这实际上会对您有所帮助,但再一次,这很难说,仅适用于您的特定文件
def get_line(file_name1,file_name2, line_start1,line_end1, line_start2, line_end2, file_name3):
f1 = open(file_name1, 'r+')
f2= open(file_name2, 'r+')
f3=open(file_name3,'w+')
line1=f1.readlines(line_start1)
line2=f2.readlines(line_start2)
line1=line1[:line_end1]
line2=line2[:line_end2]
for i in range(len(line2)):
line3="".join(line2[i].split("|")[0]).replace("/","")
for k in range(len(line1)):
line4="".join(line1[k].split("|")[0]).replace("/","")
if(line3==(line4)):
line1[k]=line2[i]
f3.writelines(line1)
f1.close()
f2.close()
f3.close()
get_line('temp/Dummy-dates-1.txt', 'temp/Separate-dates-1.txt', 0, 31, 0, 31, 'temp/Combined-1.txt')
推荐阅读
- html - CSS过渡效果向上高度不起作用
- java - Dockerized Spring Boot 不能在 Raspberry Hyperiot OS + Gitlab CI + Spring Boot 上运行
- javascript - 改变焦点上反应本机文本输入的状态
- python - 访问 Heron 中的本地文件夹
- amazon-s3 - AWS 限制对 s3 中子文件夹的访问
- java - 绑定结果不起作用弹簧启动
- html - 不需要的列布局 HTML/CSS
- javascript - VueJS for 循环创建组件,组件好像是连在一起的
- ios - iOS firebase 数据库设计问题:为云 Firestore 设计聊天应用程序的最佳方式?
- java - JavaFX:在 splashScreen 中使用不确定的进度条