1

I am just learning about file manipulation and created a simple 'text.txt' file. This file, as well as my source code('files.py') share the same parent directory('files/'). I am trying to open the file:

import os

helloFile = open('./text.txt')

However, when I run this at the command line no error is thrown but no file is opened. It seems like it is running with no problem but not doing what I want it to do. Anyone know why?

Justin
  • 1,329
  • 3
  • 16
  • 25
  • 3
    What do you mean, "no file is opened"? How do you know? What happens and how does that differ from what you expect? – Daniel Roseman Nov 20 '19 at 19:53
  • @DanielRoseman the text of the tutorial I am reading makes it sound like this should open the file in textEdit. Is this not the case? – Justin Nov 20 '19 at 19:54
  • 1
    @user3131132 no, it definitely won't. It `opens` file-like object in a memory – py_dude Nov 20 '19 at 19:55
  • Try to read the file content with helloFile.read(). If you get the file content in the command line, the file is being opened correctly. – Rafael VC Nov 20 '19 at 19:55
  • @py_dude probably should have continued on to the next page before coming here... thanks. – Justin Nov 20 '19 at 19:56
  • 2
    In a Python context, "opening" a file does not in any way correlate to double-clicking on a file in your file-system and launching the default application. To "open" a file means to get a handle to a resource, with which to do further processing like reading or writing. – Paul M. Nov 20 '19 at 19:56

1 Answers1

0

Well, you should probably read() from file as you only created file descriptor object which targets the file, but didn't really do any operation on it.

also, I recommend you to use

with open('./text.txt') as f:
    helloFile = f.read()

it will automatically close file for you,

in other case you need to close file manually like below:

f = open('./text.txt')
helloFile = f.read()
f.close()
Damian
  • 548
  • 6
  • 14