使用open()时的I/O错误

1 投票
2 回答
1153 浏览
提问于 2025-04-19 06:56

class NewTab():
    def __init__(self, song_title, artist_name):
        self.song_title  = song_title
        self.artist_name = artist_name
        name1    = self.artist_name + "_" + self.song_title
        name2    = name1.replace(" ", "")
        new_file = open("~/Documents/"+name2+".txt", "a+")

tab = NewTab(raw_input("Song Title: "), raw_input("Artist Name: "))

我正在尝试创建一个新文件(假设这个文件还不存在),这个文件的名字是根据用户输入的两个字符串生成的。例如:

"Song Title: "  >> Personal Jesus
"Artist Name: " >> Depeche Mode

最终应该创建出:~/Documents/DepecheMode_PersonalJesus.txt


不幸的是,我总是遇到:

IOError: [Errno 2] No such file or director: '~/Documents/DepecheMode_PersonalJesus.txt'

我尝试了不同的打开文件模式,比如 "w""w+""r+",但是都没有成功。
我还尝试把 name1name2new_file 放到一个 __init__ 之外的方法里,像这样:

    def create_new(self):
        name1    = self.artist_name + "_" + self.song_title
        name2    = name1.replace(" ", "")
        new_file = open("~/Documents/"+name2+".txt", "a+")

tab.create_new()

但这仍然导致了完全相同的错误。
我已经把我的 /Documents 文件夹的权限设置为(所有者、组、其他人)可以 创建和删除文件
除此之外,我完全不知道为什么我无法创建这个文件。显然,它已经按照我想要的方式构建了文件名和目录,那为什么就是不创建这个文件呢?

2 个回答

2

如果你不一定需要用到"a+"模式的话,使用"wb"作为第二个参数就可以自动打开一个文件了。

foo = open("bar", "wb")
3

使用 os.path.expanduser() 函数可以把包含“~”的路径转换成完整的有效路径,然后把这个路径传给 open() 函数。

    new_file = open(os.path.expanduser("~/Documents/")+name2+".txt", "a+")

这样,“~”就会被替换成类似 /home/user 的路径,并且和其他路径部分连接在一起。

撰写回答