Python - 从文件写入另一个文件(文件没有相同的排序)

时间:2014-07-14 09:45:14

标签: python file function dictionary sorted

下面的代码允许我通过该函数传递文本文件,然后输出一个新创建的第三个文件,其中包含用户名和密码,如下所示:

文件1格式(用户名)

Username:ID:Name:Hash:::

文件2格式(密码)

Hash:Password

文件3格式(新创建的输出文件)

Username:Password

当前的当前代码非常有效,直到输入文件的排序不相同,导致输出文件结果变得不对齐且不正确。我基本上希望将输入文件中的用户名和密码输入到一个新文件中,并且在未正确排序时不要搞砸。

from itertools import izip

def merge(f1,f2,f3):

   with open(f3, "a") as outputFile:

      for line_from_f1, line_from_f2 in izip(open(f1), open(f2)):

         username = line_from_f1.split(':')[0]
         password = line_from_f1.split(':')[1]
         outputfile.write("%s:%s" % (username, password))

merge("input1.txt", "input2,txt", "output.txt")

我认为字典是要走的路,但到目前为止,我的尝试还没有成功并且遇到各种关键错误。任何帮助,将不胜感激。 :)

最好,但会产生关键错误:

def merge(f1,f2,f3):

   d1 = {}
   with open(f1, 'r') as f:
      for line in f:
         d1[line.split(':')[3]] = line.split(':')[0]

   d2 = {}
   with open(f2, 'r') as f:
      for line in f:
         d2[line.split(':')[0]] = line.split(':')[1]

   with open(f3, 'w') as f:
      for key in d1:
         f.write("{}:{}\n".format(d1[key], d2[key]))

1 个答案:

答案 0 :(得分:1)

dict1 = {}
list1 = []
fs = ":"
with open("input1.txt") as f:
    for line in f:
       list1.append(line.rstrip('\n').split(fs))

with open("input2.txt") as f:
    for line in f:
      (key, val) = line.rstrip('\n').split(fs)
      dict1[key] = val   

with open("output.txt","w") as f:
    for username, id, name, hash, b1, b2, b3 in list1:
        if hash in dict1:
            f.write("%s:%s\n"%(username,dict1[hash]))