将特定索引中的字符串从一个文件复制到将该字符串粘贴到另一个文件中的特定位置

时间:2016-06-21 21:01:30

标签: python python-3.x

我的目的是在文件1中冒号或等号之后复制一段字符串,并在冒号或等号后​​在类似位置粘贴文件2中的字符串。

例如,如果文件1具有: 用户名:Stack

文件2最初为空: username =

我希望在用户名之后将Stack复制到文件2。目前,我被困住了,不知道该怎么做。我在下面制作的程序部分不会复制用户名。我非常感谢任何意见!

with open("C:/Users/SO//Downloads//f1.txt", "r") as f1:
    with open("C:/Users/SO//Downloads//f2.txt", "r+") as f2:
        searchlines = f1.readlines()
        searchlines_f2=f2.readlines()          
        for i, line in enumerate(searchlines):
            if 'username' in line: 
                for l in searchlines[i:i+1]: 
                    ind = max(l.find(':'), l.find('='), 0) #finding index of specific characters 
                    copy_string=l[ind+1:].strip()  #copying string for file 2  
                    for l in searchlines_f2[i:i+1]:
                        if 'username' in line:
                            f2.write(copy_string)  

1 个答案:

答案 0 :(得分:1)

我认为这样的事情会以更易于维护和Pythonic的方式为您提供所需的东西。

请注意使用正则表达式以及一些字符串方法(例如startswith

import re

SOURCE_PATH = "C:/Users/SO//Downloads//f1.txt"
TARGET_PATH = "C:/Users/SO//Downloads//f2.txt"

def _get_lines(filepath):
    """ read `filepath` and return a list of strings """
    with open(filepath, "r+") as fh:
        return fh.readlines()    

def _get_value(fieldname, text):
    """ parse `text` to get the value of `fieldname` """
    try:
        pattern = '%s[:=]{1}\s?(.*)' % fieldname
        return re.match(pattern, text).group(1)
    except IndexError:
        # you may want to handle this differently!
        return None

def _write_target(filepath, trgt_lines):
    """ write `trgt_lines` to `filepath` """
    with open(filepath, "w+") as fh:
        fh.writelines(trgt_lines)

src_lines = _get_lines(SOURCE_PATH)
trgt_lines = _get_lines(TARGET_PATH)

# extract field values from source file
fields = ['username', 'id', 'location']
for field in fields:
    value = None
    for cur_src in src_lines:
        if cur_src.startswith(field):
            value = _get_value(field, cur_src)
            break

    # update target_file w/ value (if we were able to find it)
    if value is not None:
        for i, cur_trgt in enumerate(trgt_lines):
            if cur_trgt.startswith('{0}='.format(field)):
                trgt_lines[i] = '{0}={1}'.format(field, value)
                break
_write_target(TARGET_PATH, trgt_lines)