4 Replies - 722 Views - Last Post: 05 March 2015 - 10:04 AM Rate Topic: -----

#1 Maskman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 17-February 15

Can't open and read files in Python

Posted 04 March 2015 - 08:49 AM

Here's the simple code
file=open('MY.txt')
inp=file.read()
print len(inp)
print inp


It doesn't work when I create a program in notepad++ and save it, however it does in python command line. Why? Can't get it
Is This A Good Question/Topic? 0
  • +

Replies To: Can't open and read files in Python

#2 Marbelous  Icon User is offline

  • D.I.C Head

Reputation: 43
  • View blog
  • Posts: 136
  • Joined: 12-November 12

Re: Can't open and read files in Python

Posted 04 March 2015 - 09:38 AM

You code is fine (except you should close your file). Are you sure the "MY.txt" file is in the same folder as your code? How are you running the program? If you need help with Windows command line see here: https://docs.python....aq/windows.html
Was This Post Helpful? 2
  • +
  • -

#3 Hrand  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 109
  • Joined: 25-June 12

Re: Can't open and read files in Python

Posted 04 March 2015 - 09:54 PM

you should use:

with open("some_file", 'r') as data:
    print len(data.read())
    print data.read()



When you open files like this python will automatically ensure that files are closed.

This post has been edited by Hrand: 04 March 2015 - 09:54 PM

Was This Post Helpful? 1
  • +
  • -

#4 Maskman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 17-February 15

Re: Can't open and read files in Python

Posted 05 March 2015 - 07:40 AM

View PostMarbelous, on 04 March 2015 - 09:38 AM, said:

Are you sure the "MY.txt" file is in the same folder as your code? How are you running the program?


My fault. Now it works. By the way how to read a file that is in other folder, I tried to write the path, but it didn't help

View PostHrand, on 04 March 2015 - 09:54 PM, said:

When you open files like this python will automatically ensure that files are closed.


Should files be closed to reduce the "tension" Python experiences (sorry, I couldn't say it smarter)?
Was This Post Helpful? 0
  • +
  • -

#5 Marbelous  Icon User is offline

  • D.I.C Head

Reputation: 43
  • View blog
  • Posts: 136
  • Joined: 12-November 12

Re: Can't open and read files in Python

Posted 05 March 2015 - 10:04 AM

Check this out for python's os.path method: http://stackoverflow...-path-in-python

If you leave references (files, ports, hardware drivers, etc.) open you run the risk of locking up the resource, creating memory leaks or causing other unexpected behavior. Python is pretty good at managing a lot of this stuff for you but it's still good programming practice to close whatever you open.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1