[英]parse a file, appending each line at the end and removing the line from the top
[英]\n appending at the end of each line
我正在一行一行地寫一個外部文件。 每行有9列,由制表符分隔符分隔。 如果我拆分該文件中的每一行並輸出最后一列,則可以看到\\ n被追加到第9列的末尾。 我的代碼是:
#!/usr/bin/python
with open("temp", "r") as f:
for lines in f:
hashes = lines.split("\t")
print hashes[8]
最后一列的值是1或2的整數。當我運行此程序時,得到的輸出是,
['1\n']
['2\n']
我只能得到1或2。為什么在這里附加'\\ n'?
我嘗試了以下檢查以消除問題。
with open("temp", "r") as f:
for lines in f:
if lines != '\n':
hashes = lines.split("\t")
print hashes[8]
這也行不通。 我試過了if lines != ' '
。 我該如何消除? 提前致謝。
嘗試在行上使用strip刪除\\n
(換行符)。 strip
刪除前導和尾隨空格字符。
with open("temp", "r") as f:
for lines in f.readlines():
if lines.strip():
hashes = lines.split("\t")
print hashes[8]
\\ n是換行符,這是計算機知道在下一行顯示數據的方式。 如果修改數組hash [-1]中的最后一項以刪除最后一個字符,那應該沒問題。
根據平台的不同,行尾可能不止一個字符。 Dos / Windows例如使用"\\r\\n"
。
def clean(file_handle):
for line in file_handle:
yield line.rstrip()
with open('temp', 'r') as f:
for line in clean(f):
hashes = line.split('\t')
print hashes[-1]
當我想保留前導空白時,我更喜歡rstrip()
。 那並使用生成器函數來清理我的輸入。
由於每行有9列,因此第8個索引(即第9個對象)具有換行符,因為下一行開始。 只是拿走:
print hashes[8][:-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.