0

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:

  1. open file: i got this part
  2. *do not print or ignore any line that starts with "#": i think i got this part (fread2)

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:

  1. ask user to input a text: completed
  2. from fread2 output - use the user "input" value and if value exit, then print that line only: failed!!

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?

sendoh
  • 13
  • 7
  • Can you explain the meaning of "*from fread2 output - use the user "input" value and if value exit, then print that line only*"? Do you want to check if the input equals one line of the text file? – Calaf Aug 02 '20 at 08:18
  • hi - sorry im new to python. thats correct! im trying to use the "fread2" output to find the user input. if the user input exist in fread2, then print the line. thanks! – sendoh Aug 02 '20 at 08:27
  • the value in text will be `test` but the value in x will include `\n` so it will never be the same. Also fread2 will be a concatenated string. If you print fread2 you will see the difference. – Joe Ferndz Aug 02 '20 at 08:32
  • hi joe - sorry there was a typo in if test == "":, that's meant to be "text" NOT "test" – sendoh Aug 02 '20 at 08:38
  • the for loop will pull each character. You are going to compare each char to what's in the input string. That will never give you the desired result. Instead you may want to read the line. fread2 is a string so for loop will pick each char for you – Joe Ferndz Aug 02 '20 at 08:41

2 Answers2

1

Your fread2 is a single string, so when you call for x in fread2 you are iterating on every single letter, not on every row of the file. You can see this by doing:

for x in fread2:
    print(x)

You have to save all the lines in a list or iterate on the file rows.

EXAMPLE

Try to follow this code:

fopen=open('file1.txt',mode='r+')
fread=fopen.read()

fread2=[]

for line in fread.splitlines():
    if not line.startswith('#'):
        fread2.append(line) #this is important! 
                            #If you write "+=" you'll iterate on every single letter

text=input("Enter text: ")
for x in fread2:
    if text in x:
        print("I've found "+x)
fopen.close()

If the user write "2", your output will be:

output example


UPDATE

As requested in the comments, If you want to check if the user input equals a file line you have to replace

if text in x:

with

if text==x:

So, if the user write "text", the lines "text2", "text3" etc. will be not printed!

Here is an output example:

output 2 example

Calaf
  • 1,133
  • 2
  • 9
  • 22
0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    "*So of course it's easy to see that the condition will never hold true.*". If the user wrote a single character (in this case "e"), the condition would be verified. Yes, that's not what he wants, and the entire contents of the file would be printed instead of a single line... But it is not entirely correct to say that this condition will never be True. – Calaf Aug 02 '20 at 09:26
  • @Calaf that's hard to argue with! You are definitely right. I will change the wording to be more accurate – Tomerikoo Aug 02 '20 at 09:29
  • @Tomerikoo - working and the output is correct. one problem though is when in put is "test" it prints, all line with "test" in it, however, if input is "test4" the output is fine. Enter text: test test test1 test2 test3 test4 test6 Enter text: test4 test4 – sendoh Aug 02 '20 at 09:35
  • @Tomerikoo, in the above code, if you replace `if text in line:` with `if text == line`, you will get the result you are looking for – Joe Ferndz Aug 02 '20 at 09:58
  • @sendoh your question was not clear about this part and so I followed your code. Of course checking using `in` is partial and will work if the text is **somewhere** in the string. If you want exact matches it should be `==` of course – Tomerikoo Aug 02 '20 at 10:33
  • @Temerikoo thank you! - also thank you to the other guys who help me on this problem very helpful. thank you guys for helping me on this. For now this is resolved. cheers – sendoh Aug 02 '20 at 13:44