Search code examples
pythonfile-handling

trying to get an output from a file using the user input value then print the value in python


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?


Solution

  • 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.