Home > database >  Why is my code writing something twice while reading a file
Why is my code writing something twice while reading a file

Time:10-17

I'm working on a code that sends mails to the persons given in the text file. This is the text file:

X,[email protected]
Z,[email protected]

This is my code:

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

The output should be:

X
[email protected]
Z
[email protected]

But instead it is:

X
[email protected]
X
[email protected]
Z
[email protected]
Z
[email protected]

Why is that? How can I fix it?

CodePudding user response:

You're iterating over the columns in every row, but not using the column value:

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

CodePudding user response:

Please have a look on this solution. I believe this is more elegant and efficient than the current one. Don't just rely on line break splitting. Instead get all the data in form of lines already split by \n(line break) and then use the content as per your requirements.

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

CodePudding user response:

You need to only iterate on list 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])

To make it simpler, you can read your file line by line and process it at the same time. The strip() method removes any leading (spaces at the beginning) and trailing (spaces or EOL at the end) characters.

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