簡體   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