【问题标题】:Nothing writing to file in python没有在python中写入文件
【发布时间】:2022-12-09 07:26:20
【问题描述】:

尝试用 python 编写文件,但每当我打开它时,文件只包含“无”一词

finally:
        if ord(position[0]) == 83 or ord(position[0]) == 115:
            print("SAVED")
            with open('Battleshipsave.txt','w') as f:
#this line writes to a new file and adds the board to the save file. 
                print("")
                f.write(str(print_board(board, True)))
                #this is a debugging line to ensure that the file is written correctly
                print("")
                exit()

【问题讨论】:

  • 可能是因为您的 print_board 函数返回 None。
  • @kaya3 你的意思是肯定的
  • 如果 print_board() 包含 print() 声明,那些将不是被写入文件。只有返回结果将写入文件。 return 有什么功能吗?

标签: python python-3.x


【解决方案1】:

看起来问题出在 print_board 函数上。如果函数只返回 None,那么将它写入文件只会写入“None”这个词。

要解决此问题,您可以尝试修改 print_board 函数以返回板的字符串表示形式而不是打印它。然后,您可以将 print_board 函数的返回值写入文件。这是您如何做到这一点的示例:

def print_board(board, debug=False):
    # Print the board to the console
    # ...

    # Return the string representation of the board
    return str(board)

#...

with open('Battleshipsave.txt','w') as f:
    # Write the return value of the print_board function to the file
    f.write(print_board(board, True))

或者,您可以使用 print 函数的文件参数将电路板直接写入文件,而无需使用 f.write 方法。这是您如何做到这一点的示例:

def print_board(board, debug=False, file=None):
    # Print the board to the console or to the specified file
    print(board, file=file)

#...

with open('Battleshipsave.txt','w') as f:
    # Use the `file` parameter of the print function to write the board to the file
    print_board(board, True, file=f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2016-05-17
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2016-06-04
    相关资源
    最近更新 更多