-1

Whenever I try to access .txt file using python, I get an error:

Traceback (most recent call last):
File "C:/Users/monty/AppData/Local/Programs/Python/Python38-32/tess.py", line 1, in
f1=open("d:\test.txt")
OSError: [Errno 22] Invalid argument: 'd:\test.txt'

Screenshot of error

Please help!

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49

3 Answers3

2

Specify the path using double backward slash instead of single slash(i.e backward slash is escape charactor)

fp = open('D:\\test.txt')

use single forward slash

fp = open('D:/test.txt')
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

In normal Python string literals, a backslash followed by some character has a special meaning. (Search for "string literals" and "escape sequence" or see here.) In this case, \t is the tab character. Try this:

>>> print("d:\test.txt")
d:  est.txt

So, when you try to open "d:\test.txt", you're not opening the file test.txt in the root directory of the d drive but the file dtabtest.txt in the current working directory.

There are multiple solutions to this. E.g. use a raw string literal: r"d:\test.txt".

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
0

In python open() function basically needs 3 parametres: filename,mode and encoding. You have specified the filename but you still need to specify the mode. There are many modes but you will basically need 3 of them:

"w" ->(write mode) creates file and if file exists creates empty file "a" ->(append mode) creates file and if file exists appends new data to previous data "r" ->(read mode) reads precreated file.

and encoding parametre is for seeing the chracters correct: ascii -> for english alphabet utf-8 -> for most of the langugages in the world (use this)

So all in all you should use open function like this choose which fits your purpose:

fp=open("filename.txt","w",encoding="utf-8")
fp=open("filename.txt","a",encoding="utf-8")
fp=open("filename.txt","r",encoding="utf-8")