[英]Python - Read second column from file
我的輸入文件有兩列。 我試圖在第二個for循環中打印inputdata1.txt
的第二列。 但我的代碼不起作用。 有人可以告訴我該怎么辦?
with open('inputdata1.txt') as inf:
for line in inf:
parts = line.split() # split line into parts
if len(parts) > 1: # if at least 2 parts/columns
print parts[1] # print column 2
這假設列由空格分隔。
函數split()可以指定不同的分隔符。 例如,如果列用逗號分開,
你會使用line.split(',')
在上面的代碼。
注意:使用with
打開文件會在完成后自動關閉 ,或者如果遇到異常 。
你可以這樣做。 Separator
是文件用於Separator
的字符,例如制表符或逗號。
for line in open("inputfile.txt"):
columns = line.split(separator)
if len(columns) >= 2:
print columns[1]
快點'骯臟
如果安裝了AWK:
# $2 for the second column
os.system("awk '{print $2}' inputdata1.txt")
使用課程
上課:
class getCol:
matrix = []
def __init__(self, file, delim=" "):
with open(file, 'rU') as f:
getCol.matrix = [filter(None, l.split(delim)) for l in f]
def __getitem__ (self, key):
column = []
for row in getCol.matrix:
try:
column.append(row[key])
except IndexError:
# pass
column.append("")
return column
如果inputdata1.txt
看起來像:
hel lo wor ld wor ld hel lo
你會得到這個:
print getCol('inputdata1.txt')[1]
#['lo', 'ld']
補充筆記
pyawk
獲取更多awk功能 subprocess.Popen
dirty方法,請使用subprocess.Popen
getCol('inputdata1.txt', delim=", ")
filter
刪除空值或取消注釋pass
f = open("file_to_read.txt") # open your file
line = f.readline().strip() # get the first line in line
while line: # while a line exists in the file f
columns = line.split('separator') # get all the columns
while columns: # while a column exists in the line
print columns # print the column
line = f.readline().strip() # get the next line if it exists
使用此代碼,您可以訪問每行的所有列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.