Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python解析文件_Python_File_Parsing_Io_Save - Fatal编程技术网

python解析文件

python解析文件,python,file,parsing,io,save,Python,File,Parsing,Io,Save,我有一个包含用户名和电子邮件的文件,格式如下: 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)

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

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)
但我不知道如何将结果存储在文件中。 我总是得到新文件中的最后一个电子邮件地址

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

您可以使用该模块(因为您的数据看起来是逗号分隔的,至少在您的示例中是这样):


试着这样做:

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

IP
应该是
MAIL
?1)
address
将是拆分后的值列表,2)
文件。readlines
在每行末尾保留
\n
。hum代码回显a:TypeError:只能将列表(而不是“str”)连接到地址行hum上的列表,我在文件中查找这种类型的输出:pbellyer@gmail.com\npbellyer@gmail.com\npbellyer@gmail.com\我不需要昏迷!和
line.split()
splits on…?@Kirk Strauser:是的,修复了这个问题。你为什么要剥离
单词[1]
,然后再添加
\n
?旁注:我完全同意你的方法。只是为了可能对这些事情感到疑惑的新用户而挑剔而已。:-)@柯克·斯特劳斯:嗯。。。偏执狂?如果他在原始文件中有任何多余的空格,现在他不会了。+1,但我会添加
(line.split(','),用于inf中的line If
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()
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)