【问题标题】:How Do You Make a Permanent File in Python Using Code? - Repl.it如何使用代码在 Python 中制作永久文件? - Repl.it
【发布时间】:2020-04-01 12:01:07
【问题描述】:

我正在尝试使用代码为每个使用我的程序的新人创建两个文件。到目前为止,我有:

import os
playeritems = 'PlayerFiles/PlayerItems'
playergold = 'PlayerFiles/PlayerGold'
file_number = '7'
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
    #do stuff
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
    #Fails to find the file.

但是在这段代码运行之后,这些文件就不再存在了。如何使文件在使用后永久存在?我查看了网站that briefs you on files,,但没有帮助。感谢您的时间和考虑!

错误发生在第二个 with 语句上。文件inventory.7.txt 不存在!

The entire code, if you want to take a look.

【问题讨论】:

  • 嗯,文件应该存在,你确定你的代码中没有其他影响文件的东西吗?
  • 为什么要写入文件?使用sqlite。从长远来看,它要简单得多。
  • 复制实际文本,而不是张贴图片。
  • @FrasherGray:显示一个程序,该程序创建一个文件,关闭它,然后失败重新打开它以供阅读。这样我们就可以看到失败,而不是“文件不再存在”。
  • @FrasherGray:更近一点。合并这两个示例,尽可能只使用一个文件,使用pass 作为with 正文(如果可行),并提供错误回溯。

标签: python file save repl.it


【解决方案1】:

我一定是目录有问题,因为

with open("inventory.%s.txt" % file_number, "w") as f, open("gold.%s.txt" % file_number, "w") as g:

永久制作文件。我实际上不需要文件夹,所以我可以处理任何目录。

【讨论】:

    【解决方案2】:

    如果目录不存在则创建,makedirs 创建所有子目录

    import os
    playeritems = 'PlayerFiles/PlayerItems'
    playergold = 'PlayerFiles/PlayerGold'
    
    #check if directory exists else create new
    if not os.path.exists(playeritems):
        os.makedirs(playeritems)
    if not os.path.exists(playergold):
        os.makedirs(playergold)
    
    file_number = '7'
    with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
        #do stuff
    with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
        #will  find the file
    

    【讨论】:

      【解决方案3】:

      我在这里看到的问题是文件给定路径中的目录尚不存在,您正在尝试使用“打开”动态创建它们,但是不可能这样做。

      解决这个问题的方法是检查文件路径是否真的存在,如果存在则打开文件,如果不存在则创建目录和完整路径。

      对于您的示例,代码如下:

      import os
      playeritems = str(os.getcwd())+'/PlayerFiles/PlayerItems/'
      playergold = str(os.getcwd())+'/PlayerFiles/PlayerGold/'
      file_number = '7'
      
      #check if PlayerItem path exist, if not create directories that are needed
      if not os.path.exists(os.path.dirname(playeritems)):
          try:
              os.makedirs(os.path.dirname(playeritems))
              print("created PlayerItem path")
          except OSError as exc: 
              if exc.errno != errno.EEXIST:
                  raise
      #check if PlayerGold Path exist, if not create directories that are needed
      if not os.path.exists(os.path.dirname(playergold)):
          try:
              os.makedirs(os.path.dirname(playergold))
              print("created PlayerGold Path")
          except OSError as exc: 
              if exc.errno != errno.EEXIST:
                  raise
      
      with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
          #do stuff
          print("inventoryfile and goldfile created!")
      with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
          #do Stuff
          print("Reopened playeritem inventory file")
      

      【讨论】:

      • 我向你保证目录存在。
      • 但你可能是一个人。我调用目录的方式有问题吗?
      • 您是否尝试过在使用 Windows 时在路径中使用反斜杠“\”而不是前斜杠“/”,因为这段代码在我的 macOS 上运行良好?如果还没有,可以通过 playergold=playergold.replace("/","\") 和 playeritems=playeritems.replace("/","\") 之类的方法来完成
      • 你能给我提供有错误的控制台输出吗
      • 说不存在
      【解决方案4】:

      在我的测试中,这绝对是目录的问题。

      如果文件的父目录不存在,Python 将拒绝创建该文件:

      >>> from pathlib import Path
      >>> my_dir = Path('directory_base')
      >>> with open(my_dir / 'example.txt', 'w') as f:
      >>>    f.write('Hi there!')
      
      FileNotFoundError: [Errno 2] No such file or directory: 'directory_base\\example.txt'
      

      这很容易通过创建目录来解决。 pathlib.Path 对象有一个方便的方法称为 mkdir() 可以一次创建任何和所有父目录:

      >>> from pathlib import Path
      >>> my_dir = Path('directory_base')
      >>> my_dir.mkdir(parents=True, exist_ok=True)
      >>> with open(my_dir / 'example.txt', 'w') as f:
      >>>    f.write('Hi there!')
      >>> with open(my_dir / 'example.txt') as f:
      >>>    print(f.read())
      
      'Hi there!'
      

      parents=True 表示应该创建任何和所有父目录,exist_ok 表示如果该目录已经存在,Python 不应该抛出异常。

      【讨论】:

      • 这给了我错误:TypeError: Unsupported operand type for: % Poxispath and string 编辑:哦,但你没有用我的代码做到这一点,所以你不会得到那个错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2021-02-01
      相关资源
      最近更新 更多