I'm trying to learn python and I wrote this script, that not shows me the right output.. What am i missing?
I have a text file like this:
test
test1
test2
test3
test4
#test5
test6
#test7
#test8
TASK 1:
Here is my code:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])
print(fread2)
fopen.close()
Output:
test
test1
test2
test3
test4
test6
Note: test5, 7 and 8 did not print. Success!
TASK 2:
See the following code:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])
text=input("Enter text: ")
for x in fread2:
if text == "":
continue
if text in x:
print(x)
fopen.close()
Output
Enter text: test
Where I'm wrong?
As mentioned in the comments, the fread2
variable is one big string containing all lines. When you iterate over a string, you iterate over its characters. So an example iteration of your loop is:
if "test" in "e":
print(x)
It's easy to see that this is not what you were going for.
To solve this, you can iterate through the lines by doing:
for x in fread2.split("\n"):
But, personally I think a more elegant solution would be to save the lines in a list to begin with, and only change the way you print it:
with open('file1.txt',mode='r+') as fopen:
fread = [line.strip() for line in fopen if not line.startswith('#')]
# first assignment
print(*fread, sep='\n')
#second assignment
text = input("Enter text: ")
for line in fread:
if text == line:
print(line)
Note that I used with
to open the file which is the idiomatic way of doing so.