2011-06-03 52 views
3

我正在處理一個簡單的導入例程,該例程將文本文件轉換爲用於python系統的json文件格式。從Python中的文本文件中讀取行(windows)

 
import json 

# Open text file for reading 
txtFile = open('Boating.Make.txt', 'r') 

# Create picklist obj 
picklistObj = dict() 
picklistObj['name'] = 'Boating.Make' 
picklistObj['items'] = list() 

i = 0 
# Iterate through each make in text file 
for line in txtFile: 
    picklistItemObj = dict() 
    picklistItemObj['value'] = str(i) 
    picklistItemObj['text'] = line.strip() 
    picklistItemObj['selectable'] = True 
    picklistObj['items'].append(picklistItemObj) 
    i = i + 1 
txtFile.close() 

picklistJson = json.dumps(picklistObj, indent=4) 
print picklistJson 

picklistFile = open('Boating.Make.json', 'w') 
picklistFile.write(picklistJson) 
picklistFile.close() 

我的問題是,爲什麼我需要「帶」?我以爲Python應該神奇地知道我現在在任何環境下的換行常量。我錯過了什麼嗎?

我應該澄清一下,我正在閱讀的文本文件是一個ASCII文件,其中包含以\ r \ n分隔的文本行。

回答

3

Python在枚舉行時保留新行字符。例如,列舉一個文本文件,如

foo 
bar 

,當你得到兩個字符串:"foo\n""bar\n"。如果您不想要終端換行符,請致電strip()

我不喜歡這種行爲的方式。

+0

看起來你是對的。如果我使用'U'作爲文本顯式打開文件並不重要,則行爲是相同的。這似乎與「通用新線」心態不一致。 – feathj 2011-06-03 17:19:09

0

您需要strip(),因爲「for line in file:」保留行結束符。它沒有在文檔中明確說明(至少在我看到的2.71文檔中)。但它的功能類似於file.readline(),它明確聲明它保留了換行符。

1

請參閱this

Python通常使用通用 新行支持構建;提供'U'將文件打開爲 作爲文本文件,但行 可以通過以下任一終止: Unix行尾約定'\ n', Macintosh約定'\ r',或者 Windows約定'\ r \ n'

+0

在讀取文件時,顯然將「U」附加到文件打開模式不會帶入迭代器(for語句)。將我的文件打開模式修改爲'rU'沒有任何區別。 – feathj 2011-06-03 16:54:00

0

嘗試在Python解釋器下面看到的語言做什麼:

open('test1.txt', 'wb').write(b'Hello\nWorld!') 
open('test2.txt', 'wb').write(b'Hello\r\nWorld!') 
print(list(open('test1.txt'))) # Shows ['Hello\n', 'World!'] 
print(list(open('test2.txt'))) # Shows ['Hello\n', 'World!'] 

Python不識別正確的換行。而不是在字符串上使用strip,您可能需要改爲編寫myString.replace('\n', '')。檢查文檔:

>>> help(str.strip) 
Help on method_descriptor: 

strip(...) 
    S.strip([chars]) -> str 

    Return a copy of the string S with leading and trailing 
    whitespace removed. 
    If chars is given and not None, remove characters in chars instead. 

>>> help(str.replace) 
Help on method_descriptor: 

replace(...) 
    S.replace(old, new[, count]) -> str 

    Return a copy of S with all occurrences of substring 
    old replaced by new. If the optional argument count is 
    given, only the first count occurrences are replaced. 
+0

如上所述,調用strip和replace方法實際上沒有區別。 – feathj 2011-06-03 16:55:07

+0

如果你的行首有空白,需要保留的行結束,'strip'不足以保證數據的完整性。如果你正在讀取行,你可能想調用'myString.strip('\ n')'至少保留前導和尾隨空白對你很重要。 – 2011-06-03 18:58:40

+0

這是真的。澄清的好處。 – feathj 2011-06-03 20:08:04