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

2024-04-25 00:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

任何帮助都将不胜感激。:)


Tags: 文件txtforaswithlineusernamepassword
3条回答

这是使代码正常工作所需的最小更改:

def merge(f1,f2,f3):
  with open(f3, "a") as outputFile:

     with open(f1) as usernameFile:
        for line in usernameFile:
           username = line.split(':')[0]
           lastname = line.split(':')[3]
           outputFile.write(username)

        with open(f2) as passwordFile: 
           for line in passwordFile:
              lN, password = line.split(':')
              if lN == lastname: outputFile.write(password[1]) 

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

但是,这个方法不是很好,因为它会多次读取一个文件。我会继续为第二个文件制作一个字典,以姓氏为键。字典在这种情况下很有帮助。字典可以按照如下方式进行先验处理:

^{pr2}$

我刚用这些文件运行了以下程序:

f1.txt格式

Username0:DOB:Firstname:Lastname0:::
Username1:DOB:Firstname:Lastname1:::
Username2:DOB:Firstname:Lastname2:::
Username3:DOB:Firstname:Lastname3:::

f2.txt格式

Lastname0:Password0
Lastname1:Password1
Lastname2:Password2
Lastname3:Password3

得到了输出:

Username0:Password0

Username1:Password1

Username2:Password2

Username3:Password3

{我应该在最后一行中加上}所有的内容都是空白的。如果不调用merge(...函数,则不会有任何输出。在

从文件i/o中提取数据,然后可以使用不同的提取函数重用merge()。在

import itertools as it
from operator import itemgetter    
from contextlib import contextmanager

def extract(foo):
    """Extract username and password, compose and return output string

    foo is a tuple or list
    returns str

    >>> len(foo) == 2
    True
    """
    username = itemgetter(0)
    password = itemgetter(1)
    formatstring = '{}:{}\n'
    item1, item2 = foo
    item1 = item1.strip().split(':')
    item2 = item2.strip().split(':')
    return formatstring.format(username(item1), password(item2))

@contextmanager
def files_iterator(files):
    """Yields an iterator that produces lines synchronously from each file

    Intended to be used with contextlib.contextmanager decorator.
    yields an itertools.izip object

    files is a list or tuple of file paths - str
    """
    files = map(open, files)
    try:
        yield it.izip(*files)
    finally:
        for file in files:
            file.close()


def merge(in_files,out_file, extract):
    """Create a new file with data extracted from multiple files.

    Data is extracted from the same/equivalent line of each file:
        i.e. File1Line1, File2Line1, File3Line1
             File1Line2, File2Line2, File3Line2

    in_files --> list or tuple of str, file paths
    out_file --> str, filepath
    extract --> function that returns list or tuple of extracted data

    returns none
    """
    with files_iterator(in_files) as files, open(out_file, 'w') as out:
        out.writelines(map(extract, files))
##        out.writelines(extract(lines) for lines in files)

merge(['file1.txt', 'file2.txt'], 'file3.txt', extract)

Files_Iterator是一个With Statement Context Manager,它允许多个同步文件迭代,并确保文件将被关闭。这是一个很好的开始阅读-Understanding Python's "with" statement

如果文件排序相同(即用户在两个文件中以相同的顺序出现),请使用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。然后用键lastname和值file2创建第二个字典。然后迭代任一dict的键并打印两个值。在

相关问题 更多 >