python解析文件

标签 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)

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

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

最佳答案

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)

关于python解析文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11148020/

相关文章:

python - boost python C++函数调用另一个函数错误

python - 如何在替代包名称下安装 Python wheel? (在我的具体情况下,PyCryptodome 在 "Cryptodome"包名下)

python - 从 python 脚本检查程序是否存在

linux - 在 Linux PAM 模块中允许/转义空格

python - 如何使用 NumPy 字符串格式化程序打印 NumPy 数组,其中输出字符串取决于数组值?

c - 用户在 C 中输入 int 文件得到 'Access violation'

php - 具有 laravel 4 应用程序的 Vagrant VM,新文件夹和子目录的 mkdir() 文件权限被拒绝

java - 属性文件在 Java 中返回为 null

python - 正则表达式 python dataframe 元素

python - 使用 Pandas 库将历史 Metatrader CSV 数据导入 Python(日期/时间解析)