繁体   English   中英

Python - 将行范围(由值确定)从文本文件复制到新文本文件

[英]Python - Copy range of rows (determined by value) from text file to new text file

我正在尝试编写一个脚本,该脚本可以找到要从一个文本文件复制到另一个文本文件的开始行和结束行。 我的代码(有点)有效,但有一些问题......

  • 我找到了开始 (#04) 但我不知道如何找到结束行,所以我目前只添加 100 行
  • output 是用“\n”代替分页符的一行。

作为一个新的编码器,我确信有更多 eloquent 和有效的方法来编程这个。

任何建议将不胜感激。

  • 通用汽车网
from tkinter.filedialog import askopenfilename

#01 ask name of read file and open it
filename = askopenfilename()
fp = open(filename, 'r')

#02 open write file (would be good to prompt for name)
outf = open('/Users/gmonet/Desktop/TechSupport/output_file3.txt', 'w')

#03 read the read file
lines = fp.readlines()

#04 find the string that will determine the start range to copy
for row in lines:
    word = 'Tech Support SubSection =  "service usage"'
    if  row.find(word) != -1:
        row2start = lines.index(row)

#05 copy 100 lines to the write file, starting at row2start
for line in lines:
    outf.write(str(lines[row2start:row2start+100]).splitlines())

#06 close both files
fp.close()
outf.close()

当我运行代码时,它返回一行很长的行,其中包含许多“\n”。 我也没有按值指定范围的结束(只捕获 200 行。

你在找这样的东西吗?

end = len(lines)
for out_l in lines[row2start:end+1]:
    outf.write(out_l)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM