Python - 从另一个文件写入新文件

标签 python file function input

我希望必须将 File1 的第一个字段(用户名)和第二个字段(密码)输出到函数期间创建的第三个文件中,但我无法做到这一点。 :(

文件的格式总是相同的:

文件 1:

Username:DOB:Firstname:Lastname:::

文件2:

Lastname:Password

我当前的代码:

def merge(f1,f2,f3):
   with open(f3, "a") as outputFile:
      with open(f1) as usernameFile:
         for line in usernameFile:
            line = line[:-3]
            username = line.split(':')
            outputFile.write(username[0])
      with open(f2) as passwordFile:
         for line in passwordFile:
            password = line.split(':')
            outputFile.write(password[1])

merge('file1.txt', 'file2.txt', 'output.txt')

我希望将 File1 中的用户名和 File2 中的密码写入 File3,布局如下:

Username:Password
Username:Password
Username:Password

如有任何帮助,我们将不胜感激。 :)

最佳答案

如果文件排序相同(即用户在两个文件中出现的顺序相同),请使用 tip in this answer在您的示例中同时遍历两个文件,而不是一个接一个地遍历。

from itertools import izip

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))

如果文件的排序不同,首先创建一个字典,其中键 lastname 和值 username 来自 file1。然后使用 file2 中的键 lastname 和值 password 创建第二个字典。然后遍历任一字典的键并打印两个值。

关于Python - 从另一个文件写入新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24700076/

相关文章:

c++ - 错误 : name lookup of 'i' changed for ISO 'for' scoping

python - 根据字符串列过滤分组数据框中的行

python - 如何在 TensorFlow 中使用 parallel_interleave

c++ - C++中的ifstream和ofstream错误

c++ - 如何在计算机中搜索文件和文件夹

R:使用 if/else 将列附加到具有不同长度对象的列表中

java - 我需要一些有关 Java 撤消功能的帮助

python - 从 Pandas 数据框中的字符串系列中获取总字数

python - 模块未找到错误: No module named 'mdptoolbox'

C++ 程序不从文件中读取字符