[英]Python .readline()
我正在使用Power Shell和NotePad ++學習使用艱難的方法學習Python。
我已經到了我正在使用.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
前面有一個白盒子?
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")
readline()輸出始終包含末尾的行尾字符。 你可以用repr()函數看到它們:
print repr(bl.readline())
在大多數情況下,您想要剝離它們:
bl.readline().rstrip('\r\n')
如果您不關心行的開頭/結尾的常規空格,可以將其簡化為:
bl.readline().strip()
根據theamk,jonrsharpe,Martijn Pieters和Nitu的建議我嘗試了以下腳本:
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'文件中相同的文本,但這次我手動輸入了所有六行(而不是粘貼上一文檔中的文本)
我的輸出現在如下:
$ python "new 1.py" test2.py
Text1 1 Line 1
Text2 2 Line 2
3 Text3 ´Line 3´
4 Text4 ´Line 4´
這正是我對此腳本的預期輸出。 非常感謝大家幫助我解決這個問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.