简体   繁体   English

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

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

I'm trying to write a script that can find the start and end rows to copy from one text file to another.我正在尝试编写一个脚本,该脚本可以找到要从一个文本文件复制到另一个文本文件的开始行和结束行。 My code works (sort of) but with a few issues...我的代码(有点)有效,但有一些问题......

  • I found the start (#04) but I can't figure out how to find the end row, so I am currently just adding 100 rows我找到了开始 (#04) 但我不知道如何找到结束行,所以我目前只添加 100 行
  • The output is one line with "\n"s instead of page breaks. output 是用“\n”代替分页符的一行。

As a new coder, I am sure there is a more eloquent and effective way to program this.作为一个新的编码器,我确信有更多 eloquent 和有效的方法来编程这个。

Any advice will be greatly appreciated.任何建议将不胜感激。

  • GM.net通用汽车网
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()

When I run the code, it returns one very long line with many "\n"'s.当我运行代码时,它返回一行很长的行,其中包含许多“\n”。 I also haven't specified the end of the range by value (just capturing 200 lines.我也没有按值指定范围的结束(只捕获 200 行。

Are you looking for something like this?你在找这样的东西吗?

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