Opening a File Outside PyCharm IDE - Read Line by Line

Hello...

Let me begin by saying that I'm new to Python and to PyCharm.  I'm using Python 3.3.3 and PyCharm 3.0.2 CE on Mac OS X Mavericks.  I have a text file that I would like to read line by line.  The file itself can be very large at times.  Of course I've researched as much as I can using all the familiar search engines with no luck before creating this post.  This is how I'm trying to reference the file I wish to read line by line:

text_file = os.path.isfile("/<user>/Documents/my_file.txt")
     #do something to each line in the text file

I get the following error message:
FileNotFoundError: [Errno 2] No such file or directory: '/<user>/Documents/my_file.txt'

Could anyone recommend the proper method I should use to read a text file line by line I'm referencing in PyCharm?  I apologize if a previous post has been created asking the same question.  Any suggestions would be helpful.  Thank you!
2 comments
Comment actions Permalink
Here's what I am doing when I encounter an unexpected file not found problem:
  1. Open the terminal
  2. ls /<user>/Documents/my_file.txt
Make sure that you copy & paste the exact same path from the error message. If it prints out ls: /<user>/Documents/my_file.txt: No such file or directory, then there is either a subtle typo in the path to the file or the file really does not exist.

To read the text file, you could just do something like this:
fname = '/<user>/Documents/my_file.txt'
if os.path.isfile(fname):
    println("Found file '{}'".format(fname))
    with open(fname, 'r') as f:
        for line in f:
            print line

Please note that os.path.isfile returns a whether the path is a file or not and stores it in text_file. This is not the variable you'd want to use in the open call (because it's not the path).
0
Comment actions Permalink

file=open("/root/exact path of the fileand with extension")

print(file.read())

with out module it will work

NOTE:check the uppercase and lowercase of the file while giving path

0

Please sign in to leave a comment.