簡體   English   中英

python閱讀文本文件

[英]python reading text file

我有一個文本文件,我需要每列,最好是字典或列表,格式為:

N       ID   REMAIN        VERS          
2 2343333   bana           twelve    
3 3549287   moredp       twelve        
3 9383737   hinsila           twelve           
3 8272655   hinsila           eight        

我努力了:

crs = open("file.txt", "r")
for columns in ( raw.strip().split() for raw in crs ):  
    print columns[0]

結果='超出索引錯誤'

還嘗試過:

crs = csv.reader(open(file.txt", "r"), delimiter=',', quotechar='|', skipinitialspace=True)
    for row in crs:
                   for columns in row:
                             print columns[3]

這似乎是將每個字符串作為列讀取,而不是每個“字”

我想得到四列,即:

2
2343333
bana
twelve

分成單獨的詞典或列表

任何幫助都很棒,謝謝!

這對我來說很好:

>>> crs = open("file.txt", "r")
>>> for columns in ( raw.strip().split() for raw in crs ):  
...     print columns[0]
... 
N
2
3
3
3

如果要將列轉換為行,請使用zip

>>> crs = open("file.txt", "r")
>>> rows = (row.strip().split() for row in crs)
>>> zip(*rows)
[('N', '2', '3', '3', '3'), 
 ('ID', '2343333', '3549287', '9383737', '8272655'), 
 ('REMAIN', 'bana', 'moredp', 'hinsila', 'hinsila'), 
 ('VERS', 'twelve', 'twelve', 'twelve', 'eight')]

如果您有空行,請在使用zip之前對其進行過濾。

>>> crs = open("file.txt", "r")
>>> rows = (row.strip().split() for row in crs)
>>> zip(*(row for row in rows if row))
[('N', '2', '3', '3', '3'), ('ID', '2343333', '3549287', '9383737', '8272655'), ('REMAIN', 'bana', 'moredp', 'hinsila', 'hinsila'), ('VERS', 'twelve', 'twelve', 'twelve', 'eight')]
>>> with open("file.txt") as f:
...    c = csv.reader(f, delimiter=' ', skipinitialspace=True)
...    for line in c:
...        print(line)
... 
['N', 'ID', 'REMAIN', 'VERS', ''] #that '' is for leading space after columns.
['2', '2343333', 'bana', 'twelve', '']
['3', '3549287', 'moredp', 'twelve', '']
['3', '9383737', 'hinsila', 'twelve', '']
['3', '8272655', 'hinsila', 'eight', '']

或者,老式的方式:

>>> with open("file.txt") as f:
...     [line.split() for line in f]
...
[['N', 'ID', 'REMAIN', 'VERS'],
 ['2', '2343333', 'bana', 'twelve'],
 ['3', '3549287', 'moredp', 'twelve'],
 ['3', '9383737', 'hinsila', 'twelve'],
 ['3', '8272655', 'hinsila', 'eight']]

並獲取列值:

>>> l
[['N', 'ID', 'REMAIN', 'VERS'],
 ['2', '2343333', 'bana', 'twelve'],
 ['3', '3549287', 'moredp', 'twelve'],
 ['3', '9383737', 'hinsila', 'twelve'],
 ['3', '8272655', 'hinsila', 'eight']]
>>> {l[0][i]: [line[i] for line in l[1:]]  for i in range(len(l[0]))}
{'ID': ['2343333', '3549287', '9383737', '8272655'],
 'N': ['2', '3', '3', '3'],
 'REMAIN': ['bana', 'moredp', 'hinsila', 'hinsila'],
 'VERS': ['twelve', 'twelve', 'twelve', 'eight']}
with  open("path\sample1.csv") as f:
    for line in f:
        print line

//逐行讀取文件

只需使用列表列表

import csv

columns = [[] for _ in range(4)]  # 4 columns expected

with open('path', rb) as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        for i, col in enumerate(row):
            columns[i].append(col)

或者如果列數需要動態增長:

import csv

columns = []

with open('path', rb) as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        while len(row) > len(columns):
            columns.append([])
        for i, col in enumerate(row):
            columns[i].append(col)

最后,您可以使用以下方式打印列:

for i, col in enumerate(columns, 1):
    print 'List{}: {{{}}}'.format(i, ','.join(col))

這個怎么樣?

f = open("file.txt")

for i in f:
    k = i.split()
    for j in k:
        print j

你可以使用這樣的列表理解:

with open("split.txt","r") as splitfile:
    for columns in [line.split() for line in splitfile]:
        print(columns)

然后,您將使用2d數組,允許您按照自己喜歡的方式對其進行分組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM