0

I don't understand why something this simple isn't very intuitive.

This is what I have so far:

    print("Enter name of file on Desktop:")
    filename = sys.stdin.readline()


    directory = os.path.join(os.path.expanduser("~"),"Desktop")
        for subdir, dirs, files in os.walk(directory):
            for file in files:
                if file.startswith(filename):
                    f = open(os.path.join(subdir, file),'r+', encoding="Latin-1")
                    data = f.read()
                    print(data)
                    f.close()

Why can't I pass the sys.stdin that was assigned to the variable filename to the 'if' statement:

   `if file.startswith(filename):`? 

I tried:

    if file.startswith(str(filename)):
    if file.startswith("'" + filename + "'")
    if file.startswith(filename):

no options seem to "go through" and no errors pop up.

It just pretends like I didn't pass anything. Any help? Thanks.

2
  • Format code by indenting by four spaces. Only use backticks for small pieces of code. Commented Jun 4, 2017 at 19:02
  • Also, any time you get errors, you need to post them Commented Jun 4, 2017 at 19:02

1 Answer 1

2

A line, whether read from stdin or from a file, includes a newline character. It seems unlikely that any of your filenames end in a newline.

But don't use sys.stdin.readline to get input from the user. Use the appropriately-named input function:

filename = input("Enter name of file on Desktop:")

(Note, in Python 2.x you should use raw_input rather than input.)

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it was something stupid. Thanks. I got it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.