我尝试只将.txt列表中的名字打印到新的文本文件中。
.txt列表看起来像这样(每对名称都在自己的行上,名称多于此处显示的名称):
Smith, James
Doe, John
White, Susan
这是我目前的代码:
fname = input("Please enter the file name for your list of names: ")
infile = open(fname,"r")
data = infile.read()
outfile = open("student-firstnames.txt", "w")
first = data.split(",")[-1]
print(first, file=outfile)
print("First names have been written to student-firstnames.txt.")
这只给了我最后一个名字,但我想要一个只有名字的完整列表。我能做些什么来实现这个目标?
答案 0 :(得分:1)
您可以尝试以下方法:
first = [i.split(", ")[1] for i in data.split("\n")]
print(first, file=outfile)
这会按换行符拆分数据,然后获取逗号之后的部分,这是第一个名称。
答案 1 :(得分:1)
您可以迭代文件对象以一次处理一个文件的每一行:
with open(fname) as infile:
for line in infile:
...
例如,您可以使用它来获取文件中每行的名字列表:
with open(fname) as infile:
first_names = [line.strip('\n').split(', ')[1] for line in infile]
答案 2 :(得分:0)
您也可以尝试将其命名为索引1。
fname = input("Please enter the file name for your list of names: ")
infile = open(fname,"r")
outfile = open("student-firstnames.txt", "w")
x = '\n,'.join([line.split(', ')[1].strip() for line in infile])
outfile.write(x)
outfile.close()
infile.close()
<强>输出:强>
James
,John
,Susan
答案 3 :(得分:0)
在Python 3中你可以这样做:
fname = input("Please enter the file name for your list of names: ")
with open(fname, "r") as infile, open("student-firstnames.txt", "w") as outfile:
for line in infile:
firstname = line.strip().split(', ')[-1]
print(firstname, file=outfile)