运行比较两个csv文件的python脚本后,剩下一个新的csv文件,该文件仅列出了新学生的电子邮件地址。 (稍后将用于在我们的电子邮件系统中自动创建新用户)。
但是,我需要获取仅具有电子邮件地址的csv文件,并基于电子邮件地址中的信息,创建一个新的csv文件,该文件的标题为firstname,lastname,email,然后具有适当的数据用于每行。
示例:
原始csv(newemails.csv)
john.doe@mydomain.com
terry.jackson@mydomain.com
silly.sally@mydomain.com
新的CSV文件应如下所示:
firstname, lastname, email
John, Doe, john.doe@mydomain.com
Terry, Jackson, terry.jackson@mydomain.com
Silly, Sally, silly.sally@mydomain.com
这是我当前的代码,为我提供了newemails.csv文件
import csv
import os
import subprocess
def newemails():
for line in fileinput.input(r'C:\gamwork\currentstudents.csv', inplace=1):
print(line.lower(), end='')
with open(r'C:\gamwork\previoususers.csv', 'r') as t1,
open(r'C:\gamwork\currentstudents.csv', 'r') as t2:
fileone = t1.readlines()
filetwo = t2.readlines()
with open(r'C:\gamwork\newemails.csv', 'w') as outFile:
for line in filetwo:
if line not in fileone:
outFile.write(line)
我真的不确定从这里开始怎么做,任何建议都将不胜感激!
答案 0 :(得分:0)
您可以尝试以下操作: 如果您的文件包含
john.doe@mydomain.com
terry.jackson@mydomain.com
silly.sally@mydomain.com
然后您可以执行以下操作:
with open('mydata.csv', 'r') as f, open('out.csv', 'w') as out_file:
out_file.write('First name, last name, email\n')
for line in f:
names, email = line.split('@')[0], line
first, last = names.split('.')
new_line = f'{first}, {last}, {email}'
out_file.write(new_line)
with open('out.csv', 'r') as out_file:
print(out_file.read())
输出:
First name, last name, email
john, doe, john.doe@mydomain.com
terry, jackson, terry.jackson@mydomain.com
silly, sally, silly.sally@mydomain.com
答案 1 :(得分:0)
使用pandas
可以轻松实现
请在下面找到一个示例。
import pandas as pd
df = pd.read_csv('test3.csv', header=None, names=['Email'])
df['FirstName'] = [x.split('.')[0].title() for x in df['Email']]
df['LastName'] = [x.split('.')[1].split('@')[0].title() for x in df['Email']]
df = df.drop('Email', 1)
print(df)
df.to_csv('students.csv')
或其他解决方案是
import pandas as pd
def createFirstLastNames(row):
firstLast = row['Email'].split('@')[0]
firstName = firstLast.split('.')[0].title()
lastName = firstLast.split('.')[1].title()
return pd.Series({
'FirstName' : firstName,
'LastName' : lastName
})
df = pd.read_csv('test3.csv', header=None, names=['Email'])
df1 = df.merge(df.apply(lambda row: createFirstLastNames(row), axis=1), left_index=True, right_index=True)
df1 = df1.drop('Email', 1)
print(df1)
df1.to_csv('students.csv')
输出如下
FirstName LastName
John Doe
Terry Jackson
Silly Sally