2

次の形式のユーザー名と電子メールを含むファイルがあります。

pete,pbellyer@gmail.com

メールのみを保持したいので、次のような正規表現を使用することを考えました:

import re,sys

Mailfile = sys.argv[1]

file = open(Mailfile, "r")

for MAIL in file.readlines():
   tmp = re.split("\n+", MAIL)
   m = re.match( ',(.+)', MAIL)
   m.group(0)

しかし、結果をファイルに保存する方法がわかりません。私は常に新しいファイルの最後の電子メール アドレスを取得します。

結果をファイルに保存する最良の方法は何ですか? ありがとう!

4

3 に答える 3

8
import sys

infile, outfile = sys.argv[1], sys.argv[2]

with open(infile) as inf, open(outfile,"w") as outf:
    line_words = (line.split(',') for line in inf)
    outf.writelines(words[1].strip() + '\n' for words in line_words if len(words)>1)
于 2012-06-21T23:36:24.050 に答える
2

csvモジュールを使用できます(少なくとも例では、データがコンマ区切りに見えるため):

import sys
import csv
with open('mail_addresses.txt', 'w') as outfile:
    for row in csv.reader(open(sys.argv[1], 'rb')):
        outfile.write("%s\n" % row[1])
于 2012-06-21T23:04:28.197 に答える
1

次のようなことを試してください:

import sys

Mailfile = sys.argv[1]
Outfile = sys.argv[2]

try:
    in_file = open(Mailfile, 'r')
    out_file = open(Outfile, 'a')

    for mail in in_file.readlines():
        address = mail.split(',')[1].strip()
        out_file.write(address+',') #if you want to use commas to seperate the files, else use something like \n to write a new line.
finally:
    in_file.close()
    out_file.close()
于 2012-06-21T23:14:51.123 に答える