Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PyCharm Help
#1
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
Reply
#2
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.
Reply
#3
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?
Reply
#4
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'
Reply
#5
Thank you snippsat! You've been very helpful.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020