读入并比较Python中的两个文件
您好,我有两个文本文件,每个文件包含关于特定结构的不同信息。两个文件中的结构都由id号标识。我想做的是读取第一个文件并跳过不符合条件的数据行。然后跳过第二个文件中不具有相同id号的行,并处理其他行。我尝试使用嵌套for循环来实现它,我也尝试将它作为两个单独的函数,但两种尝试都不起作用。我现在正试图使用下面的一个循环来完成它,但是得到了这个错误读入并比较Python中的两个文件,python,Python,您好,我有两个文本文件,每个文件包含关于特定结构的不同信息。两个文件中的结构都由id号标识。我想做的是读取第一个文件并跳过不符合条件的数据行。然后跳过第二个文件中不具有相同id号的行,并处理其他行。我尝试使用嵌套for循环来实现它,我也尝试将它作为两个单独的函数,但两种尝试都不起作用。我现在正试图使用下面的一个循环来完成它,但是得到了这个错误 UnboundLocalError: local variable 'linel' referenced before assignment 这是代码。
UnboundLocalError: local variable 'linel' referenced before assignment
这是代码。我
F = 'file1.txt'
Fl = 'file2.txt'
X = [] # Creats Data Lists
M = []
Id1 = []
Id2 = []
LC = 10
N = 11
fl = open(Fl)
fl.readline()
nlinesl = islice(fl,N)
f = open(F) #Opens file
f.readline() # Strips Header
nlines = islice(f, N) #slices file to only read N lines
for line in nlines and linel in nlinesl:
if line !='':
linel = linel.strip()
linel = linel.replace('\t','')
columnsl = linel.split()
lum = float(columnsl[1])
if lum != LC:
continue
id1 = int(columnsl[0])
Id1.append(id1)
if line !='':
line = line.strip()
line = line.replace('\t','')
columns = line.split()
id2 = int(columns[1])
Id2.append(id2)
if Id != Id2:
continue
x = columns[2] # assigns variable to columns
X.append(x)
print(X)
下面是我希望发生的一个例子
两个文件
file1= 1 1 1 1 file2 = 1 1 1 1
2 5 1 1 1 2 1 1
2 3 4 4 1 1 1 1
Lc = 5
Xa = 1
因此,只有文件1的第二行将继续存在,这意味着只有文件2中的第二行将被处理,因为它们具有相同的id
id = columns[0] for file1
及
提前感谢我不认为这是合法的语法:
for line in nlines and linel in nlinesl:
请尝试以下方法:
for line, line1 in zip(nlines, nlines1):
此外,这些变量名很难/很容易出错:)
例如:
按预期生成输出
20 200
21 201
22 202
23 203
24 204
25 205
大致如下:
ids = set()
for line in nlines:
if line != '':
cols = line.strip().replace('\t','').split()
lum = float(cols[1])
lid = int(cols[0])
if lum != LC:
ids.add(lid)
for line in nlinesl:
if line != '':
cols = line.strip().replace('\t','').split()
lid = int(cols[1])
if lid in ids:
x = cols[2]
X.append(x)
请您标记导致错误的行,并提供完整的回溯。。这将使问题更容易解决。您需要压缩双迭代器:
for line,linel in zip(nlines,nlinesl):
@K-Braffor它现在可以工作了,谢谢您zip()完成了它。我还要多读一读,谢谢!
20 200
21 201
22 202
23 203
24 204
25 205
ids = set()
for line in nlines:
if line != '':
cols = line.strip().replace('\t','').split()
lum = float(cols[1])
lid = int(cols[0])
if lum != LC:
ids.add(lid)
for line in nlinesl:
if line != '':
cols = line.strip().replace('\t','').split()
lid = int(cols[1])
if lid in ids:
x = cols[2]
X.append(x)