2015-09-04 85 views
3

我正在使用Power Shell和NotePad ++學習Python的難題。Python .readline()

我已經到了我正在使用的部分.readline(),我注意到我的函數中第一個參數的第一個字符被刪除或被空格覆蓋。我知道已經有一個問題似乎回答了這個問題(Python .readline()),但由於我對Python和Powershell完全陌生,所以我不知道如何擺弄和更改其中任何一個設置。

我寫了要執行的腳本(稱爲new 1.py)是這樣的:

from sys import argv 
script, input_filename = argv 

def foo (arg1,arg2,arg3): 
    print arg1,arg2,arg3.readline() 

def bar (arg1, arg2, arg3): 
    print arg2,arg1,arg3.readline() 

open_input_file=open(input_filename) 

foo ("Text1",1,open_input_file) 
foo ("Text2",2,open_input_file) 
bar ("Text3",3,open_input_file) 
bar ("Text4","4",open_input_file) 

與包含文本test1.py文件:

Line 1 
Line 2 
Line 3 
Line 4 
Line 5 
Line 6 

我的輸出是如下:

$ python "new 1.py" test1.py 
ext1 1 ☐ Line 1 
ext2 2 Line 2 
    Text3 Line 3 
    Text4 Line 4 

我期望的輸出是:

$ python "new 1.py" test1.py 
Text1 1 Line 1 
Text2 2 Line 2 
3 Text3 Line 3 
4 Text4 Line 4 

有人可以請解釋如何讓.readline()讀取行而不刪除或覆蓋第一個字符(有空格)嗎?爲什麼在輸出中的首都L前面有一個白盒子?

+3

嘗試'.readline()。strip()'去除可能影響輸出的任何討厭的空白字符。另外,請閱讀[風格指南](http://www.python.org/dev/peps/pep-0008/)並相應地設置代碼的格式(例如,更多合理的函數/參數名稱將會非常有幫助)。 – jonrsharpe

+2

使用'repr(bl.readline())'打印該行的調試表示。文件中的其他字節由控制檯或終端解釋爲控制字符。 –

+6

你可能想要考慮更好的變量名稱;兩個字母變量很難跟蹤。 –

回答

0

在theamk的提醒,jonrsharpe,馬亭皮特斯和逆徒我嘗試了下面的腳本:

from sys import argv 
script, input_filename = argv 

def foo (arg1,arg2,arg3): 
    print arg1,arg2,arg3.readline().strip("\r\n") 

def bar (arg1, arg2, arg3): 
    print arg2,arg1,repr(arg3.readline().strip("\r\n")) 

open_input_file=open(input_filename) 

foo ("Text1",1,open_input_file) 
foo ("Text2",2,open_input_file) 
bar ("Text3",3,open_input_file) 
bar ("Text4","4",open_input_file) 

寫下了新的test2.py文件,其中包含相同的文字作爲「test1.py」文件,但這次我鍵入了所有六行的手(而不是coppy粘貼從以前的文件文本)

我的輸出如下內容:

$ python "new 1.py" test2.py 
Text1 1 Line 1 
Text2 2 Line 2 
3 Text3 ´Line 3´ 
4 Text4 ´Line 4´ 

這正是我對這個腳本所期望的輸出。 非常感謝您幫助我解決這個問題!

1

readline()輸出始終包含結尾的行尾字符。你可以看到他們與再版()函數:

print repr(bl.readline()) 

在大多數情況下,要剝奪他們:

bl.readline().rstrip('\r\n') 

如果你不關心在該行的開始/結束常規空格,您可以將其簡化爲:

bl.readline().strip() 
+0

我曾嘗試使用任一 打印再版(arg3.readline()) arg3.readline()。rstrip( '\ r \ N')或 arg3.readline()。帶() 但是他們沒有似乎工作。 –

+0

@DouwevanderLeest請顯示代碼,您的輸入,您的輸出和您的預期輸出。只是爲了確保我們知道你的意思,當你說「它不工作」。 –

2

方法readline()從文件中讀取一整行。尾隨的換行符保留在字符串中。 您不必將readline放置兩次。如果你會這樣做,那麼你會得到像line2,line4,line6和空字符串爲arg3傳遞的結果。

爲定義的方法嘗試以下代碼。

def foo (arg1,arg2,arg3): 
    print arg1,arg2,arg3.readline().rstrip("\n") 

def bar (arg1, arg2, arg3): 
    print arg2,arg1,arg3.readline().rstrip("\n")