2017-12-18 82 views
0

我有一個文本文件。如何打印文本文件的行如果分號在末尾

Test.txt的

this is line one; this line one 

this is line two; 

this is line three 

我想打印含有分號線,但分號應該是行的末尾。

我的代碼

search = open("Test.txt","r") 
for line in search : 
    if ";" in line: 
     semi = line.split(";") 
     if semi[-1] == "\n": 
      print(line) 

輸出

this is line two; 

我的代碼工作正常,但我希望有一個更好的方式來做到這一點。 任何人都可以告訴我簡短和最pythonic的方式來做到這一點?

回答

2

可以肯定它容易

for line in search : 
    if line.endswith(';\n'): 
     print(line) 

而作爲@IMCoins注意,最好使用上下文管理with關閉您的文件,你就大功告成了工作時:

with open("Test.txt","r") as test_file: 
    for line in test_file: 
     if line.endswith(';\n'): 
      print(line) 
+0

將這項工作在Python 2.7? – sam

+0

@sam是的,我測試過了。 –

+0

謝謝....現在這段代碼工作正常,我認爲這是最短的做法 – sam

0

在第一次使用的with關鍵字打開文件:

with open('foo.txt', 'r') as f: 
    for line in f: 
     if ';' in line: 
      semi = line.split(';') 
      if semi[-1] == '\n': 
       print line 

對我來說,它是在您使用內置函數時已經大部分是pythonic,使用for循環。

+0

感謝您的回覆 – sam

0
if line[:-2] == ';\n': 
    print(line) 

正常工作的Python 2 也適用,如果線只是一個 '/ N'

+0

儘管這可能會回答這些問題,但您可能無法提供一些額外的細節並解釋答案。在目前的狀態下,這個答案是低質量的。 –

相關問題