Python拒绝打开文件,给出了unicodeescape'错误(os.path.expanduser(path)问题)

时间:2017-02-10 11:06:29

标签: python python-3.x tkinter filepath

这是我的代码。

# -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 14:47:36 2017

@author: Jose Chong
"""
import json
import tkinter

master = tkinter.Tk()
master.title("To-Do List (with saving!)")
master.geometry("300x300")

masterFrame = tkinter.Frame(master)

masterFrame.pack(fill=tkinter.X)

checkboxArea = tkinter.Frame(masterFrame, height=26)

checkboxArea.pack(fill=tkinter.X)

inputStuff = tkinter.Frame(masterFrame)

checkboxList = []

with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json') as infile:    
    checkboxList = json.load(infile)

def destroyCheckbox(checkbox, row):
    row.destroy()
    del checkboxList [checkboxList.index(str(checkbox))]

    with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json', 'w') as outfile:
        json.dump(checkboxList, outfile)

for savedCheckbox in checkboxList:
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text=savedCheckbox)
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text="x", bg="red", fg="white",
                                activebackground="white", activeforeground="red",
                                command=lambda c=savedCheckbox, r=checkboxRow: destroyCheckbox(c, r))
    deleteItem.pack(side=tkinter.RIGHT)

    with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json', 'w') as outfile:
        json.dump(checkboxList, outfile)

def drawCheckbox():
    newCheckboxInput = entry.get()
    def destroyCheckbox():
        checkboxRow.destroy()
        del checkboxList[checkboxList.index(newCheckboxInput)]
        with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json', 'w') as outfile:
            json.dump(checkboxList, outfile)                 
    checkboxList.append(newCheckboxInput)
    entry.delete(0,tkinter.END)
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text = checkboxList[-1])
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text = "x", command=lambda c=savedCheckbox, r=checkboxRow: destroyCheckbox(c, r), bg="red", fg="white", activebackground="white", activeforeground="red")
    deleteItem.pack(side=tkinter.RIGHT)

    with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json', 'w') as outfile:
        json.dump(checkboxList, outfile)


def createInputStuff():
    paddingFrame = tkinter.Frame(inputStuff, height=5)
    paddingFrame.pack(fill=tkinter.X)
    buttonDone.pack()
    inputStuff.pack()
    buttonAdd.pack_forget()
    master.bind('<Return>', lambda event: drawCheckbox())

def removeInputStuff():
    inputStuff.pack_forget()
    buttonAdd.pack()
    buttonDone.pack_forget()
    master.unbind('<Return>')


buttonDone = tkinter.Button(inputStuff, text = "Close Input", command=removeInputStuff)


buttonAdd = tkinter.Button(masterFrame, text="Add Item", command=createInputStuff)
buttonAdd.pack()


topInput = tkinter.Frame(inputStuff)
bottomInput = tkinter.Frame(inputStuff)

topInput.pack()
bottomInput.pack()

prompt = tkinter.Label(topInput, text="What do you want your checkbox to be for?")
prompt.pack()
entry = tkinter.Entry(bottomInput, bd=3)
entry.pack(side=tkinter.LEFT)
buttonConfirm = tkinter.Button(bottomInput, text="Confirm", command=drawCheckbox)
buttonConfirm.pack(side=tkinter.LEFT)

master.mainloop()

给出的错误是:

runfile('C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile/toDoList.py', wdir='C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile')
  File "C:/Users/Josalina/Desktop/Coding/Language - Python/to-do-list-to-compile/toDoList.py", line 26
    with open('C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json') as infile:
             ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

它应该做同样的事情:

# -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 14:47:36 2017

@author: Jose Chong
"""
import json
import tkinter

master = tkinter.Tk()
master.title("To-Do List (with saving!)")
master.geometry("300x300")

masterFrame = tkinter.Frame(master)

masterFrame.pack(fill=tkinter.X)

checkboxArea = tkinter.Frame(masterFrame, height=26)

checkboxArea.pack(fill=tkinter.X)

inputStuff = tkinter.Frame(masterFrame)

checkboxList = []

with open('toDoListSaveFile.json') as infile:    
    checkboxList = json.load(infile)

def destroyCheckbox(checkbox, row):
    row.destroy()
    del checkboxList [checkboxList.index(str(checkbox))]

    with open("toDoListSaveFile.json", 'w') as outfile:
        json.dump(checkboxList, outfile)

for savedCheckbox in checkboxList:
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text=savedCheckbox)
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text="x", bg="red", fg="white",
                                activebackground="white", activeforeground="red",
                                command=lambda c=savedCheckbox, r=checkboxRow: destroyCheckbox(c, r))
    deleteItem.pack(side=tkinter.RIGHT)

    with open("toDoListSaveFile.json", 'w') as outfile:
        json.dump(checkboxList, outfile)

def drawCheckbox():
    newCheckboxInput = entry.get()
    def destroyCheckbox():
        checkboxRow.destroy()
        del checkboxList[checkboxList.index(newCheckboxInput)]
        with open("toDoListSaveFile.json", 'w') as outfile:
            json.dump(checkboxList, outfile)                 
    checkboxList.append(newCheckboxInput)
    entry.delete(0,tkinter.END)
    checkboxRow = tkinter.Frame(checkboxArea)
    checkboxRow.pack(fill=tkinter.X)
    checkbox1 = tkinter.Checkbutton(checkboxRow, text = checkboxList[-1])
    checkbox1.pack(side=tkinter.LEFT)
    deleteItem = tkinter.Button(checkboxRow, text = "x", command=lambda c=savedCheckbox, r=checkboxRow: destroyCheckbox(c, r), bg="red", fg="white", activebackground="white", activeforeground="red")
    deleteItem.pack(side=tkinter.RIGHT)

    with open("toDoListSaveFile.json", 'w') as outfile:
        json.dump(checkboxList, outfile)


def createInputStuff():
    paddingFrame = tkinter.Frame(inputStuff, height=5)
    paddingFrame.pack(fill=tkinter.X)
    buttonDone.pack()
    inputStuff.pack()
    buttonAdd.pack_forget()
    master.bind('<Return>', lambda event: drawCheckbox())

def removeInputStuff():
    inputStuff.pack_forget()
    buttonAdd.pack()
    buttonDone.pack_forget()
    master.unbind('<Return>')


buttonDone = tkinter.Button(inputStuff, text = "Close Input", command=removeInputStuff)


buttonAdd = tkinter.Button(masterFrame, text="Add Item", command=createInputStuff)
buttonAdd.pack()


topInput = tkinter.Frame(inputStuff)
bottomInput = tkinter.Frame(inputStuff)

topInput.pack()
bottomInput.pack()

prompt = tkinter.Label(topInput, text="What do you want your checkbox to be for?")
prompt.pack()
entry = tkinter.Entry(bottomInput, bd=3)
entry.pack(side=tkinter.LEFT)
buttonConfirm = tkinter.Button(bottomInput, text="Confirm", command=drawCheckbox)
buttonConfirm.pack(side=tkinter.LEFT)

master.mainloop()

但只是写入不同位置的文件。我希望它适用于每个不同的用户,因此我将os.path.expanduser(path)替换为here。我几乎可以肯定我使用os.path.expanduser(path)错了,有帮助吗?我该怎么办?

顺便说一句,我已经在Documents \ joseDzirehChongToDoList \ toDoListSaveFile.json中创建了该文件。

2 个答案:

答案 0 :(得分:0)

os.path.expanduser是一个函数,这意味着您不能只是在字符串中插入文字字符串“os.path.expanduser(path)”并期望它能够正常工作。 / p>

os.path.expanduser的全部目的是将~转换为用户主目录。例如,`os.path.expanduser(“〜”)可能会返回“/ Users / Josalina”。

此外,如果在文件路径中使用反斜杠,则需要在普通字符串中转义它们(例如:"foo\\bar"),或者使用原始字符串来防止反斜杠具有特殊含义(例如: r"foo\bar")。许多人似乎不知道的是,Windows支持正斜杠,因此您也可以使用"foo/bar"

最后,在使用之前将文件名保存到变量是个好主意,这样就可以更容易地调试此问题。如果您已将变量放在文件名中,则可以添加print语句(例如:print(filename))以验证完整文件名是否符合预期。

总而言之,如果你想在你的主目录中引用“Documents \ joseDzirehChongToDoList \ toDoListSaveFile.json”,最好的方法是这样做:

filename = os.expanduser(r"~\Documents\joseDzirehChongToDoList\toDoListSaveFile.json")
with open(filename, "w") as outfile:
    ...

由于正斜杠在Windows上是有效的,你也可以这样做并删除对原始字符串的需要,并且这个代码在linux和osx上也可以保持不变的额外好处:

filename = os.expanduser("~/Documents/joseDzirehChongToDoList/toDoListSaveFile.json")

答案 1 :(得分:-1)

问题是,你没有告诉程序如何处理该文件。您正在寻找该文件,因此您应该使用:

 with open(r'C:\Users\os.path.expanduser(path)\Documents\joseDzirehChongToDoList\toDoListSaveFile.json', 'w')

r告诉python如何处理该文件。 打开文件的其他方法是:

使用w写入文件

使用A附加文件。

希望我能提供帮助:)