我希望将File1中的第一个字段(Username)和第二个字段(Password)输出到第三个文件中,该文件是在函数执行过程中创建的,但我不能这样做。:(
文件的格式始终相同,即:
文件1:
Username:DOB:Firstname:Lastname:::
文件2:
^{pr2}$我的当前代码:
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')
我希望文件1中的用户名和文件2中的密码写入文件3,布局如下:
Username:Password
Username:Password
Username:Password
任何帮助都将不胜感激。:)
这是使代码正常工作所需的最小更改:
但是,这个方法不是很好,因为它会多次读取一个文件。我会继续为第二个文件制作一个字典,以姓氏为键。字典在这种情况下很有帮助。字典可以按照如下方式进行先验处理:
^{pr2}$我刚用这些文件运行了以下程序:
f1.txt格式
f2.txt格式
得到了输出:
{我应该在最后一行中加上}所有的内容都是空白的。如果不调用
merge(...
函数,则不会有任何输出。在从文件i/o中提取数据,然后可以使用不同的提取函数重用
merge()
。在Files_Iterator
是一个With Statement Context Manager,它允许多个同步文件迭代,并确保文件将被关闭。这是一个很好的开始阅读-Understanding Python's "with" statement如果文件排序相同(即用户在两个文件中以相同的顺序出现),请使用tip in this answer在同一时间迭代两个文件,而不是在示例中一个接一个。在
如果文件的排序不相同,请首先创建一个字典,其中键
lastname
和值username
来自file1
。然后用键lastname
和值file2
创建第二个字典。然后迭代任一dict的键并打印两个值。在相关问题 更多 >
编程相关推荐