在Python文件,調用讀而不換行符
temp = open(filename,'r').readlines()
結果,其中每個元素是在文件中的線的列表。它有點愚蠢,但仍然:readlines()
也爲每個元素寫入換行符,這是我不希望發生的事情。我怎樣才能避免它?
在Python文件,調用讀而不換行符
temp = open(filename,'r').readlines()
結果,其中每個元素是在文件中的線的列表。它有點愚蠢,但仍然:readlines()
也爲每個元素寫入換行符,這是我不希望發生的事情。我怎樣才能避免它?
可以使用str.splitlines
讀取整個文件,並分割線:
temp = file.read().splitlines()
或者你可以用手剝換行:
temp = [line[:-1] for line in file]
注:這最後的解決方案僅適用如果文件以換行符結束,否則最後一行會丟失一個字符。
這種假設在大多數情況下都是正確的(特別是對於由文本編輯器創建的文件,通常做無論如何都會添加結尾換行符)。
如果你想避免這種情況,你可以在文件的末尾添加一個新行:
with open(the_file, 'r+') as f:
f.seek(-1, 2) # go at the end of the file
if f.read(1) != '\n':
# add missing newline if not already present
f.write('\n')
f.flush()
f.seek(0)
lines = [line[:-1] for line in f]
或者更簡單的辦法是strip
而不是換行:
[line.rstrip('\n') for line in file]
甚至,雖然相當難以理解:
[line[:-(line[-1] == '\n') or len(line)+1] for line in file]
這利用了事實,返回VA or
的lue不是布爾值,而是被評估爲true或false的對象。
的readlines
方法實際上等同於:
def readlines(self):
lines = []
for line in iter(self.readline, ''):
lines.append(line)
return lines
# or equivalently
def readlines(self):
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines
由於readline()
保持換行符也readlines()
保持它。
注:爲對稱readlines()
的writelines()
方法不不添加結束換行符,所以在f2.writelines(f.readlines())
產生f2
的f
完全相同的副本。
請注意''[line.rstrip('\ n')用於文件中的行]''會刪除多個尾部的''\ n''。 –
更簡單地說,''[line [:-(line [-1] =='\ n')或len(line)+1]可以替換爲''[line [:-(line [-1] =='\ n')或者None]用於文件中的行]''。 –
這些解決方案將整個文件讀入內存。將列表理解的方括號改爲括號會產生一個生成器表達式,它允許您一次一行地遍歷文件:'for line in(x.strip()for f in f):' – velotron
def getText():
file=open("ex1.txt","r");
names=file.read().split("\n");
for x,word in enumerate(names):
if(len(word)>=20):
return 0;
print "length of ",word,"is over 20"
break;
if(x==20):
return 0;
break;
else:
return names;
def show(names):
for word in names:
len_set=len(set(word))
print word," ",len_set
for i in range(1):
names=getText();
if(names!=0):
show(names);
else:
break;
import csv
with open(filename) as f:
csvreader = csv.reader(f)
for line in csvreader:
print(line[0])
temp = open(filename,'r').read().splitlines()
嘗試這種情況:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
雖然這段代碼可以解決這個問題,但是[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ
使用條:'[l.strip( '\ n \ r'),用於在升溫度]'。甚至是「rstrip」。自從這裏迭代它可以'開放',而不是'在溫度'。 – gorlum0
這個問題是對我擁有的每一個聲望評分負責 – Yotam
如果在Python 3中有一個值,可以將打開的'newline'參數設置爲那些小塊尾隨的換行符,那麼我會很好。 – jxramos