Python Forum

Full Version: PyCharm Help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I started to learn how to open files up in PyCharm; however, the file will 'open' using open(), but then nothing else in the program will execute. Not a 'for loop' or even a print('hey'). Does anyone know why? I'm trying to get through a homework exercise, but I am getting hung up on this problem. Thanks for your help!

INPUT:
fname = input("/Users/Earth/Downloads/textfile.txt")
fh = open(fname)

print('hey')
OUTPUT:
/Users/Earth/Downloads/textfile.txt
input() is for user input and you have to read() the file object
Example:
fname = input('Name of file to open: ')
file_obj = open(fname)
print(file_obj.read())
file_obj.close()
Output:
E:\div_code\new λ python f_test.py Name of file to open: textfile.txt hello world
An ideally you want to use with open() then file object close automatically.
fname = input('Name of file to open: ')
with open(fname) as file_obj:
    print(f'Name of file : {file_obj.name}\nContent of file: {file_obj.read()}')
Output:
E:\div_code\new λ python f_test.py Name of file to open: textfile.txt Name of file : textfile.txt Content of file: hello world
As i do this test textfile.txt is in same folder as f_test.py,then avoid to give path to file.
Thank you snippsat! I put the text file in the same folder as my .py and it worked! How do I make my program find the file if it is not in the same folder as my .py? Or is that too advanced for beginner python?
Just give path path to file and it should work.
fname = '/Users/Earth/Downloads/textfile.txt'
with open(fname) as file_obj:
    print(file_obj.read())
So if code over work,the same for input() just that now user have to type in path to file.
fname = input('Name of file to open: ')
with open(fname) as file_obj:
    print(file_obj.read())
If you use Windows most also have path to drive.
Code example over without drive path only work on Linux
fname = 'C:/Users/Earth/Downloads/textfile.txt'
Thank you snippsat! You've been very helpful.