我希望必须将 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/