[英]How to read a specific row and column from a text file and base decision on numeric value with python?
我有許多文本文件,形式為:
alpha 89687
beta 9564
delta 10000
我只想單獨查看每一行並評估第二列中的每個值。 如果該值不在某個范圍內,我想刪除整個文件。 我有一個文本文件,其中包含我要瀏覽的所有文件的標題。 這是我的代碼:
with open('filetitles.dat', 'r') as f:
for line in f:
with open(line, 'r+') as t:
for i, enumerate(t):
v = i == 2 and #how to specify column
if v<1 or v>100:
delete(t)
z = i == 3 and #how to specify column
if v<100 or v>120000:
delete(t)
任何幫助將不勝感激。 謝謝下面是我修改的代碼。 我無法將其轉到下一行,因為條件不滿足。
import os
with open('test.txt', 'r') as f: #file with titles of files
files=[l.strip() for l in f]
toDel=[]
for file in set(files):
with open(file, 'r+') as t: #open specific file
for line in t:
v,w = line.split()[0:2] #try to specify lines and columns
if type(v) == int and type(w) == float: #check only lines in specific format
if int(v)==1000021 and float(w)<2.5 or float(w)>3: #arbitrary values which will ensure deletion of test file
toDel.append(file)
else:
some command to go to next line
else:
some command to go to next line
for file in set(toDel):
os.remove(file) #delete files
print 'Delete:"{}"'
像這樣的東西可以作為骨架:
with open('filetitles.dat', 'r') as f:
files=[l.strip() for l in f]
toDel=[]
for file in set(files):
with open(file, 'r') as f:
for line in f: # each line of the file
w,v = line.split()[0:2] # w==col 1, v==col 2
if w=='beta' and int(v)<100000: # example test
toDel.append(file)
for file in set(toDel): # now delete all the files...
# os.remove(file) # 'set()' eliminates dups
print 'Delete: "{}"'.format(file)
編輯這是您的與建議的mod的循環:
for file in set(files):
with open(file, 'r+') as t: #open specific file
for line in t:
# use the appropriate regex to validate the line you seek
match=re.search(r'^(\d+)\s+([-+]?[0-9]*\.?[0-9]+)\s*$',line)
if match:
v=int(match.group(1))
w=float(match.group(2))
if v==1000021 and (w<2.5 or w>3.0):
toDel.append(file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.