2017-09-27 7 views
-1

私はユーザーリストとtxtファイルのリストを持っています。 ユーザーと一致する各ファイルについて、一致するファイルを「開く」し、文字列「ID NAME:」の後ろにuserの名前を追加する必要があります。私はこれを試してみたが動作しませんリスト要素をいくつかのtxtファイルに追加する

[email protected] 
[email protected] 
[email protected] 
... 
... 

:私のオリジナルファイルの

import os 
import glob 
import re 

users = ['[email protected]', '[email protected]', '[email protected]'] 

'''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:[email protected] 
CREATED:20170927T101000 
DESCRIPTION:USER 
CREATED:20170927T101000 
SEQUENCE:0 
STATUS:OK 
ID NAME: 
V:000 
Z:END 
+0

あなたの質問は何ですか?遭遇したエラー/問題は何ですか?注: 'rw'モードは存在しません。 'r +'が必要です。これはおそらく問題です –

+0

私はこの例を見ました:https://stackoverflow.com/questions/22779650/appending-a-data-in-a-specific-line-of-a-text-file-in-python 例外IOError:[errnoを2 しかし、私はR「+」と試みるが、私はこのエラーを取得 – sudosu

答えて

0

あなたはこれを試すことができ

私のファイルは、この次のとおりです。

s = ["[email protected]", "[email protected]", "[email protected]"] 
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() 
+0

機能しないリストではなく単一のファイルまたは「ユーザー」 を持っている場合の対処方法がわかりません]そのようなファイルやディレクトリはありません: '20170927.txt' – sudosu

+0

@sudosuもう一度やり直してください。私はコードを変更しました。 – Ajax1234

+0

彼は "[email protected]" ではなく "[email protected]" 私はスクリプトにこれに追加検索 " - " new_file_data = [i.strip( '\ n' を) +名前i.strip(「\ n」)で==「ID名:」もし他の私、私のためのオープン(名前+ - +ファイル名「」)で ]しかし、このスクリプトはID」の後に「ユーザー名」を追加しません。 NAME: " – sudosu

関連する問題