2015-09-08 70 views
-5

所以即時嘗試解決Python的問題。 我得到了一個帶有文字和Sybol的文本文件。但訂單是錯誤的。 爲了解決它,我需要一個腳本:python - 讀取文本文件,操作順序

  • 逐行讀取文本文件行從上到下
  • 從各行採取的最後一個字符,即使只有1個字符在該行,並將他放在Next行中,在最後一個Char之前。 (因爲當它跳轉到下一行,移動該行最後一個字符,與前行的最後一個字符將是這一行新的最後一個字符)
  • 終於寫出所有到一個新的文本文件

現在我嘗試了一些東西,但它的所有變得更長,然後我期待,所以我好奇你們可以考慮什麼樣的方法。

由於提前

PS:

我會附上一個例子,如何將文本文件要去看看這裏:

! 
cake + 
house - 
wood * 
barn /
shelf = 
town 

的目標是,在最終文件時,它看起來是這樣的:

cake ! 
house + 
wood - 
barn * 
shelf /
town = 
+2

讓我們瞭解您到目前爲止? – taesu

回答

-1
with open('input.txt') as f: 
    #this method automatically removes newlines for you 
    data = f.read().splitlines() 

char, sym = [], [] 
for line in data: 
    #this will work assuming you never have more than one word per line 
    for ch in line.split(): 
     if ch.isalpha(): 
      char.append(ch) 
     else: 
      sym.append(ch) 

#zip the values together and add a tab between the word and symbol   
data = '\n'.join(['\t'.join(x) for x in zip(char, sym)]) 

with open('output.txt', 'w') as f: 
    f.write(data) 
1

可以使用shutil.move更換與更新的內容的原始文件寫入tempfile.NamedTemporaryFile

from tempfile import NamedTemporaryFile 
from shutil import move 

with open("in.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as temp: 
    # get first symbol 
    sym = next(f).rstrip() 
    for line in f: 
     # split into word and symbol 
     spl = line.rsplit(None, 1) 
     # write current word followed by previous symbol 
     temp.write("{} {}\n".format(spl[0],sym)) 
     # update sym to point to current symbol 
     sym = spl[-1] 
# replace original file 
move(temp.name,"in.txt") 

in.txt後:

cake ! 
house + 
wood - 
barn * 
shelf/
town = 

如果你想製表符分隔使用temp.write("{}\t{}\n".format(spl[0],sym))