0

I tried to read the file from directory but i m unable to read. every time i get the same error. hello.txt is the file name and it contains the content as well. I want to read the file first and then its content line by line.

import cv2
f = open("C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r")
print(f.readline())
f.close()

.

Traceback (most recent call last):

  File "<ipython-input-9-b53fed7bb3dd>", line 3, in <module>
    f = open("C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r")

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt'
furas
  • 134,197
  • 12
  • 106
  • 148

2 Answers2

0

Have you tried using forward slash instead of backslash? Please try changing the directory string to:

"C:/Users/Kazmi-PC/OneDrive/Desktop/hello.txt"

It seems like this issue is similar to the one described here

Davide
  • 109
  • 2
  • 10
0

Try out with this code -

with open(r"C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r") as file:
    <some code>

This will tell that it is raw string.

More Information

What exactly do "u" and "r" string flags do, and what are raw string literals?

EDIT:

Python was not able to find file hello.txt which in real was getting passed as hello.txt.txt

Simple step on windows to view the extension:

  1. Press window

  2. Search "File Explorer Options"

  3. In view tab, uncheck "Hide extensions for known file types".

PySaad
  • 1,052
  • 16
  • 26