python解析fi

2024-04-28 19:41:57 发布

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

我有一个用户名和电子邮件文件,格式如下:

pete,pbellyer@gmail.com

我只想保留电子邮件,所以我想使用这样的regex:

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)

但我不知道如何将结果存储在文件中。 我总是得到新文件中的最后一个电子邮件地址。

将结果存储在文件中的最佳方法是什么? 谢谢!


Tags: 文件importrecom电子邮件格式sysmail
3条回答

试试这样的:

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()

您可以使用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])
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)

相关问题 更多 >