Python Forum

Full Version: I cannot able open a file in python ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Myself is ted,
i am trying open a text file in python using open("filename.txt") but i am seeing FileNotFoundError: [Errno 2] No such file or directory: 'new.text' this error, every time i tired to open or manipulate a file i am seeing this error.The name of file i inputted is right and i also created python file and text file In a folder and i tried to open using the above syntax still showing the same error , can anyone give me the solution ?


this is the code i am using to open a file in python:
h = open("new.text")
x = h.split()
print(x)
(Feb-10-2023, 09:39 PM)ted Wrote: [ -> ]o such file or directory: 'new.text'
new.text should not be there,as the file extension is .txt.
Also split() will not work on file object.
h = open("new.txt")
x = h.read().split()
print(x)
Output:
['Hello', 'world']
Bettter.
with open("new.txt") as fp:
    result = fp.read().split()
    print(result)
Output:
['Hello', 'world']
One can also fetch the whole content of the file with a higher level library
import pathlib
print(pathlib.Path('new.text').read_text().split())
i am seeing this error:Traceback (most recent call last):
File "/home/teddy/Videos/Python/python/2.py", line 2, in <module>
print(pathlib.Path('new.text').read_text().split())
File "/usr/lib/python3.10/pathlib.py", line 1134, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
File "/usr/lib/python3.10/pathlib.py", line 1119, in open
return self._accessor.open(self, mode, buffering, encoding, errors,
FileNotFoundError: [Errno 2] No such file or directory: 'new.text'
(Feb-10-2023, 11:25 PM)ted Wrote: [ -> ]i am seeing this error
The name of the file is probably new.txt instead of new.text. Also it could happen that the file is not in the current directory.

By default the path is relative to the current working directory of the running python process. You could pass the absolute path to the file, for example
(pathlib.Path.home()/'spam'/'eggs'/'new.txt').read_text()
i solved the problem thank you.