Well, I'm a begginer in Python coding, and at DaniWeb. My problem is: I can't open any files!

I tried:

>>> f = open('C:\teste.txt', 'w')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    f = open('C:\teste.txt', 'w')
IOError: [Errno 22] invalid mode ('w') or filename: 'C:\teste.txt'
>>> f = 'C:\teste.txt'
>>> open(f)

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    open(f)
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\teste.txt'
>>> open ('C:\teste.txt', 'r')

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    open('C:\teste.txt', 'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\teste.txt'

Tried in Python Shell & Cmm Line...
Using Python 2.6.4 for WinXp installed in C:\Python 26

Dani AI

Generated

On Windows, the backslash in a Python string starts an escape sequence, so \t becomes a tab and \n a newline. That is why 'C:\teste.txt' is misread and open() raises an error; it is not a permissions or shell issue. Safer options are to use a raw string (prefix r) or forward slashes, which Windows APIs accept. See the language reference on string escape handling and raw strings, and note that raw strings cannot end with a single backslash. String and bytes literals and FAQ: raw strings ending in backslashes.

Two patterns you can apply immediately:

# Raw string and a context manager
with open(r"C:\teste.txt", "w") as f:
    f.write("hello")
# If you need a trailing backslash in a raw string, use a workaround:
# path = r"C:\temp" + "\\"
# or: os.path.join(r"C:\temp", "")
# Pathlib (avoids manual separators and works cross‑platform)
from pathlib import Path
p = Path("C:/teste.txt")   # forward slashes are fine on Windows
p.write_text("hello", encoding="utf-8")

For building paths robustly, prefer pathlib.Path or os.path.join() over manual concatenation. pathlib documentation, os.path.join.

Recommended Answers

All 2 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.