【问题标题】:Append list element to some txt file将列表元素附加到某个 txt 文件
【发布时间】:2017-09-27 12:49:58
【问题描述】:

我有一个用户列表和一个 txt 文件列表。 对于与用户匹配的每个文件,我需要“打开”匹配的文件并在字符串“ID NAME:”之后附加用户名。

我的文件是这样的:

j.smith@google.com-20170927.txt
a.cooper@google.com-20170925.txt
s.king@google.com-20170926.txt
...
...

我尝试了这个但不起作用:

import os
import glob
import re

users = ['j.smith@google.com', 'a.cooper@google.com', 's.king@google.com']

'''Get user without mail ext'''
a = []
for itemc in (users):
    itemc = itemc.rpartition('@')[0]
    a.append(itemc)

'''Get all txt file'''
c = []
txt_file = []
os.chdir("C:\txt")
files = glob.glob('*.txt')
for file in files:
    txt_file.append(file)
c = []

''' Append user to txt file -NOT WORK '''
for itema in users:
for itemb in (txt_file):
    if re.search(itema, itemb):
        c.append(itemb)
        for txtfile in c:
            with open(txtfile, 'rw') as f:
                lines = f.readlines()
            for i, line in enumerate(lines):
                if line.startswith('ID NAME:'):
                    line[i] = line[i].strip() + (itema)
            f.seek(0)
            for line in lines:
                f.write(line)

我的原始文件示例:

A:CALFSL
VERSION:1.0
SCALE:G
B:REQUEST
C:010101010
START:20170929T000000
END:20170929T000000
STAMP:20170927T101000
MAIL:mailto:user@domain.com
CREATED:20170927T101000
DESCRIPTION:USER
CREATED:20170927T101000
SEQUENCE:0
STATUS:OK
ID NAME:
V:000
Z:END

【问题讨论】:

  • 您的问题是什么?遇到什么错误/问题?注意:rw 模式不存在。你需要r+。这可能是问题
  • 我看到了这个例子:stackoverflow.com/questions/22779650/…。但我不知道如果有一个列表而不是单个文件或“用户”我尝试使用 'r+' 但不起作用

标签: python


【解决方案1】:

你可以试试这个:

s = ["j.smith@google.com-20170927.txt", "a.cooper@google.com-20170925.txt", "s.king@google.com-20170926.txt"]
for name, filename in [i.split('-') for i in s]:
    new_file_data = ["ID NAME:"+name[:name.index("@")]+"\n" if i.startswith("ID NAME:") else "MAIL:mailto:"+name + "\n" if i.startswith("MAIL") else i for i in open(name+filename)]
    final_file = open(name+filename, 'w')
    for line in new_file_data:
        final_file.write(line)
    final_file.close()

【讨论】:

  • 我得到这个错误:IOError: [Errno 2] No such file or directory: '20170927.txt'
  • @sudosu 请现在再试一次。我已经修改了代码。
  • 他搜索“j.smith@google.com20170927.txt”而不是“j.smith@google.com-20170927.txt”我添加到脚本“-”new_file_data = [i。 strip('\n')+name if i.strip('\n') == "ID NAME:" else i for i in open(name+'-'+filename)] 但是这个脚本没有添加“ “ID NAME:”之后的用户名”
  • @sudosu 请发布一个示例,说明您的原始文件是什么样的,最终文件应该是白色的。
  • 感谢您的耐心等待。请看这里我想要什么:pastebin.com/agSbd76Z
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多