Home > Software design >  os module not opening a file
os module not opening a file

Time:02-26

Using the Python os Module, it is not opening this File (bouncpass.txt). When I run the code, nothing appears, I don't get no error or nothing. What is wrong with the below code?

import os

bouncfile = os.open('C:\\hoopers\\pickup\\towns\\bouncpass.txt', os.O_RDONLY)

CodePudding user response:

import os
bouncfile = os.open('C:\\hoopers\\pickup\\towns\\bouncpass.txt', os.O_RDONLY)
str = os.read(bouncfile, os.path.getsize(bouncfile))
print(str.decode())

with os.open() file you need to use os.read() to read the content of file. I use dummy file so check ouptut screen enter image description here

bouncfile = open('some.txt', 'r')
for val in bouncfile.readlines():
    print(val.rstrip())

you can use simple open() method to open file and you don't need read method to read content file with simple open() method.

Output: enter image description here

CodePudding user response:

There may be a reason you are choosing os over open().

But as M. Twarog mentioned, you can bypass the need of the os library to open and read files by using the open() built-in method in python.

Just for additional info, another way of using open() is by using the with keyword in Python.

with open('\path\to\text', 'r') as f:
    info = f.read()

What is the python keyword "with" used for?

  • Related