0

This is a code for accessing a file inside a folder using with open() as:{} option.

with open("DATABASE\password.txt") as _2_:
    password=_2_.readlines()
with open("DATABASE/names.txt") as _3_:
    names=_3_.readlines()
with open("DATABASE\email.txt") as _4_:
    email=_4_.readlines()

In this code, if I put "DATABASE\names.txt", as I did for password and email; instead of "DATABASE/names.txt"; it does not work. Please Tell me the reason for the same.

Kishore_Vasan
  • 11
  • 1
  • 7
  • If you indent your code 4 spaces it will appear as a code block distinct from normal text. Its hard to read the code now. – Malonge Feb 04 '15 at 17:59

2 Answers2

1

You need to add another backslash. Example: open("path\\to\\file.txt")

Your errors are happening because you need to escape the backslash by adding another one. Such a thing won't happen with /.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

You need to escape the \, use raw string r or forward slashes as you have already tried:

"DATABASE\\names.txt" # double \
r"DATABASE\names.txt" # raw string
"DATABASE/names.txt" # use forward slashes

\n is a newline character.

In [7]: print "DATABASE\names.txt" # interpreted as two lines
DATABASE
ames.txt

In [8]: print r"DATABASE\names.txt"
DATABASE\names.txt

A backslash has a special meaning in python, it is used to escape characters.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321