Reputation: 1488
I have this code
import urllib.request
fw = open("myfile.txt", "r")
red = fw.read()
line = red.split("\n")
blue = line.split("@")[0]
i=0
while i<len(blue):
try:
try code is here
try:
try code is here
except:
print(blue[i] + " is " + "having e1")
except:
print(blue[i] + " is " + "having e2")
i+=1
I am getting
Errno 2 No Such File or Directory
when I try to run my file. However, when I remove the line blue = line.split("@")
it works fine.
What I want to do is to repeat this code on all the lines of myfile.txt
- so I split \n
first to get one line of the file then I want to get the characters before @
in this line and put it in the string blue
I can't understand why it work when I remove blue = line.split("@")
Any help would be appreciated.
Upvotes: 0
Views: 435
Reputation: 26037
line = red.split("\n")
blue = line.split("@")[0]
When you do red.split("\n")
, you obtain a list of lines. So line
in your code is essentially a list of lines.
To demonstrate:
>>> red = '''\
... This is line 1
... This is line 2
... This is line 3'''
>>> red.split('\n')
['This is line 1', 'This is line 2', 'This is line 3']
You cannot perform split
on a list.
Instead, get each item of line
and perform split on it.
Here is a list-comprehension way of dealing with the issue:
blue = [x.split('@')[0] for x in line]
In above code, we iterate through each item in line
(which is a list of lines as already explained). In each iteration, x
takes each value out of line
. x
takes one line, does split on that, then on next iteration, takes next line from list, splits and continues till end.
Upvotes: 1