alamba
alamba

Reputation: 117

Renaming file extension in Python 2.7

I am trying to rename the extension of a text file to zip as advised here. The file is being written based on a base64 encoded response from a server, which I am decoding before writing.

This is my code snippet:

f = open("response.txt","wb")
f.write(json.loads(response.text)['Binary'].decode('base64'))
f.close()
file1 = "C:\Users\xyz\response.txt"
base = os.path.splitext(file1)[0]
os.rename(file1, base + ".zip")

I am getting the following error even though the file is in the absolute path specified in my code:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

Please assist.

Upvotes: 0

Views: 127

Answers (2)

dot.Py
dot.Py

Reputation: 5147

Try changing this line:

file1 = "C:\Users\xyz\response.txt"

to this:

file1 = "C:\\Users\\xyz\\response.txt"

or this:

file1 = r"C:\Users\xyz\response.txt"

Upvotes: 0

Kevin
Kevin

Reputation: 76184

file1 = "C:\Users\xyz\response.txt"

"\r" is a single character representing a carriage return. You probably don't have a file that has a carriage return in its name. If you intended that to be a backslash followed by an R, use raw strings.

file1 = r"C:\Users\xyz\response.txt"

Upvotes: 2

Related Questions