为什么我的代码在读取文件时写了两次

Why is my code writing something twice while reading a file

我正在编写一个代码,可以向文本文件中指定的人发送邮件。 这是文本文件:

X,y@gmail.com
Z,v@gmail.com

这是我的代码:

with open("mail_list.txt","r",encoding ="utf-8") as file:
    a = file.read()

b = a.split("\n")
d = []

for i in b:
    c = i.split(",")
    d.append(c)

for x in d:
    for y in x:
        print(x[0])
        print(x[1])

输出应该是:

X
y@gmail.com
Z
v@gmail.com

但它是:

X
y@gmail.com
X
y@gmail.com
Z
v@gmail.com
Z
v@gmail.com

这是为什么? 我该如何解决?

您正在遍历每一行中的列,但未使用列值:

for x in d:
    for y in x:
        print(y)

请查看此解决方案。我相信这比当前的更优雅和高效。不要仅仅依靠换行符拆分。而是以已被 \n(换行符)分割的行形式获取所有数据,然后根据您的要求使用内容。

lines = []
with open('mail_list.txt') as f:
    lines = f.readlines()
for line in lines:
    info = line.split(',')
    print(info[0])
    print(info[1])

您只需迭代列表 d

with open("mail_list.txt", "r", encoding ="utf-8") as file:
    a = file.read()

b = a.split("\n")
d = []

for i in b:
    c = i.split(",")
    d.append(c)

for x in d:
    print(x[0])
    print(x[1])

为了更简单,您可以逐行读取文件并同时处理它。 strip() 方法删除任何前导(开头的空格)和尾随(末尾的空格或 EOL)字符。

with open("mail_list.txt", "r", encoding ="utf-8") as file:
    for line in file:
        line_s = line.split(",")
        print(line_s[0])
        print(line_s[1].strip())