我需要从文件中取出行并将其附加到另一个文件的行尾,如果它们具有通用性(在我的情况下是相同的路径)。
第一个文件中的示例行(' out.txt'):
\vol\vol1\path1: The inherited access control list (ACL) or access control entry (ACE) could not be built. (119)
\vol\path2: Access is denied. (2)
\vol\vol24\path27: Access is denied. (401) Could not convert the name of inner file or directory (111)
文件中的示例行我希望以名为' concat.txt'的新文件的形式附加到(' fixed_inv.txt'):
42 sggisnap013.example.com xskld_$FOLw \vol\vol1\path1
42 sggisnap013.example.com /vol/vol7 /vol/vol7
42 sggisnap013.example.com HOME \vol\vol0\home
正如您在两个文件中看到的那样,存在共性。它恰好是路径:\vol\vol1\path1
有时您会看到使用不同服务器名称的相同路径(sggisnap013.example.com),如:
44 tkgisnstor012.nomura.com /vol/vol1
42 sggisnap013.example.com xskld_$FOLw /vol/vol1
在执行追加之前,它必须具有相同的服务器和路径。
然而,在其他情况下,共性将是一条不同的道路。
我已经写了这段代码:
err = []
inv = []
with open('out.txt', 'r') as f1:
for line in f1: #for each line
split_line = line.split(' ')
index_f1 = split_line[0]
err = index_f1
with open('fixed_inv.txt', 'r') as f2:
for line in f2: #for each line
split_line = line.split('\t') #split the line by each tab, call that split_line
index_f2 = split_line[3] #key2 will hold the item occuring at split index 3
inv.append(index_f2)
with open('concat.txt', 'w') as file_out:
for line in err:
for line in inv:
if err == inv:
file_out.write(line)
else:
continue
注意:
'out.txt'
是我追加'fixed_inv.txt'
的文件。结果将是一个新文件。
然而,当我运行这个时,我会得到一些有趣的东西,但不是我想要的东西:
\\\\\\\\aappppsssss__33\\\\ttrrssssspprrsssss
我很感激如何正确地做这件事。谢谢。
答案 0 :(得分:0)
with open('concat.txt', 'w') as file_out:
for line_e in err:
for line_i in inv:
if line_e == line_i:
file_out.write(line_i)
else:
continue
答案 1 :(得分:0)
看看,它可能会给你一些想法:
def common(file1, file2, file3):
'''
file1 - name for the source file (out.txt)
file2 - name for second source file (fixed_inv.txt)
file3 - name for output file (concat.txt)
'''
with open(file1, 'r') as f1:
with open(file2, 'r') as f2:
with open(file3, 'a') as f3:
for l1,l2 in zip(f1,f2):
path1 = l1[:l1.index(':')]
paths_list = [x.strip() for x in l2.split(' ') \
if x.startswith("\\") or x.startswith("/")]
for line in paths_list:
#if line.find('\\\\') != -1:
#line = line.replace("\\\\", '\\' )
if line == path1:
f3.write(path1)
我们有3个参数file1, file2, file3
,它们是您的源文件和输出文件。我们同时打开它们并开始处理数据。
path1 = l1[:l1.index(':')]
此行存储out.txt
的路径。例如,如果您的第一行是
`\vol\vol1\path1: The inherited access control list (ACL) or access control entry (ACE) could not be built. (119)`
然后path1是
`path1="\vol\vol1\path1"`
然后我们从fixed_inv.txt
中的每一行获取所有路径。例如,如果您的行是
42 sggisnap013.example.com /vol/vol7 /vol/vol7
然后列表将是:
paths_list=['/vol/vol7', '/vol/vol7']
就我所知,最后一个标准是这样的:
for line in paths_list:
if line == path1: # replace with your condition
f3.write(path1)
在此,我们将out.txt
的路径与ixed_inv.txt
和#your condition is True
的所有可能路径进行比较,而不是写入输出文件concat.txt
顺便说一下,通过这次检查
`#if line.find('\\\\') != -1:
#line = line.replace("\\\\", '\\' )`
如果有任何需要,您可以将'\\vol\\vol1\\path1'
路径替换为'\vol\vol1\path1'
。