Just a quick one- I'm writing code that asks the user for a filename and checks that it exists. If it does it has to print the file's contents, if not print a message.

import os
fileName = raw_input("Enter the name of the file: ")
if os.path.exists(fileName) == True:
    fileName.read()
else:
    print "error, that file does not exist"

As fileName is now a string, how do I read the contents of the user's input?

Thank you

You must open the file

content = open(fileName).read()

No error but no output either

import os
fileName = raw_input("Enter the name of the file: ")
if os.path.exists(fileName) == True:
   outFile = open(fileName).read()
else:
    print "error, that file does not exist"

No error but no output either

And it means file is empty, especially if you opened with write option

Have tried mutiple files, all with content, and still no output

Have tried mutiple files, all with content, and still no output

content_string = open(fileName).read()
print(content_string) # <---- OUTPUT
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.