例如,假設我有一個名為 test.txt 的檔案,內容如下,數千個字串相互疊加。
I will come one day.
What did you do.
I will go home.
OK, I'll come too.
I'm waiting then.
I will come.
我想要的是前兩行并排寫。當它們并排書寫時,將我想要的特殊字符放在它們之間。所以像這樣
I will come one day. ■What did you do?
I'll go home. ■Okay, I'll come too.
I'm waiting then. ■I'll come.
我需要一個代碼,以便我可以像這樣列印它們。我已經找了整整四個小時,但我終于放棄了,我要去睡覺了。提前謝謝大家。
uj5u.com熱心網友回復:
如果您的輸入行數是偶數,或者如果最后一行因奇數行而丟失也沒關系,請嘗試以下操作:
>>> with open("src.txt") as src, open("output.txt", "wt") as output:
... while (line1 := src.readline()) and (line2 := src.readline()):
... output.write(f"{line1.strip()} # {line2.strip()}\n")
源檔案.txt:
I will comeone day.
What did you do.
I will go home.
OK, I'll come too.
I'm waiting then.
I will come.
輸出.txt:
I will comeone day. # What did you do.
I will go home. # OK, I'll come too.
I'm waiting then. # I will come.
或者,如果您也需要使用奇數,請嘗試以下操作:
>>> with open("src.txt") as src, open("output.txt", "wt") as output:
... while (line1 := src.readline()) and (line2 := src.readline()):
... output.write(f"{line1.strip()} # {line2.strip()}\n")
... if line1 and not line2:
... output.write(line1)
源檔案.txt:
I will comeone day.
What did you do.
I will go home.
OK, I'll come too.
I'm waiting then.
I will come.
Meow
輸出.txt:
I will comeone day. # What did you do.
I will go home. # OK, I'll come too.
I'm waiting then. # I will come.
Meow
當文本檔案中只有一行時,第二個會拋出錯誤,但既然你說了數千,應該沒問題。
uj5u.com熱心網友回復:
列印檔案中的所有行,中間有特殊字符
special_char = "#"
with open("text.txt", "r") as txt:
lines = txt.readlines() # read all lines in the file
lines = [line.strip("\n") for line in lines] # remove newline charactor from its end
n = len(lines) #find the number of lines
if n%2 == 0: # if number of lines is even
for i in range(0,n,2): # go from 0 to n with 2 steps at a time, i.e, i = i 2
print(f"{lines[i]} {special_char} {lines[i 1]}")
else: # if number of lines is odd
for i in range(0,n-1,2):
print(f"{lines[i]} {special_char} {lines[i 1]}")
print(lines[-1]) # print the last line in the list
輸出:
偶數行
I will come one day. # What did you do.
I will go home. # OK, I'll come too.
I'm waiting then. # I will come.
奇數行
I will come one day. # What did you do.
I will go home. # OK, I'll come too.
I'm waiting then. # I will come.
See you then
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362120.html
