写入文件

写入文件
def loadSubredditConfig (self):
    self.builder.get_object ('cbxR').remove_all ()
    path = os.path.join (xdg.BaseDirectory.xdg_config_home, 'RedThat', 'subreddits')

    if (os.path.exists (path)):
        file = open (path, 'r+')
        for line in file.readLines ():
            self.builder.get_object ('cbxR').append_text (line.strip ().replace (' ', ''))
    else:
        file = open (path, 'w') # Problem here
        file.write ('')
        self.builder.get_object ('cbxR').append_text ('')

Traceback (most recent call last):
  File "bin/gtkreddit", line 33, in <module>
    gtkreddit.main()
  File "/home/robin/Ubuntu One/Python/gtkreddit/gtkreddit/__init__.py", line 33, in main
    window = GtkredditWindow.GtkredditWindow()
  File "/home/robin/Ubuntu One/Python/gtkreddit/gtkreddit_lib/Window.py", line 35, in __new__
    new_object.finish_initializing(builder)
  File "/home/robin/Ubuntu One/Python/gtkreddit/gtkreddit/GtkredditWindow.py", line 63, in finish_initializing
    self.loadSubredditConfig ()
  File "/home/robin/Ubuntu One/Python/gtkreddit/gtkreddit/GtkredditWindow.py", line 236, in loadSubredditConfig
    file = open (path, 'w')
IOError: [Errno 2] No such file or directory: '/home/robin/.config/RedThat/subreddits'

我想要创建文件。
尝试过、、、、w。全部都抛出相同的错误。arww+a+

答案1

/home/robin/.config/RedThat/在尝试在目录中创建文件之前,请确保该目录存在。

答案2

您需要确保所有父目录都存在,即您想要创建文件的路径。您可以使用os.makedirs来完成此操作。您可能还应该避免使用,xdg.BaseDirectory因为python-xdg上游实际上不再维护。您可以改用dirspec.basedir,这是python-dirspecUbuntu 中的包。

相关内容