尝试写入文件,但是我收到一条错误,说写入需要文件对象而不是字符串

时间:2017-08-24 16:30:11

标签: python

感谢所有反馈,错误现已修复。

我正在尝试使用此代码写入文件。

import datetime
from datetime import datetime
ctime = str(datetime.now())
try:
    open("pyth_log.txt", "w")
    file.write("pyth_log.txt")
    file.write("-------")
    file.write("LOG")
    file.write(ctime)
    file.write("-------")
    file.close()
except:
    print("Unable to open file")
    raise

我得到错误:

TypeError: descriptor 'write' requires a 'file' object but received a 'str'

我还尝试使用" pyth_log.txt"运行代码。不是引号,但它给了我错误:

NameError: name 'pyth_log' is not defined

3 个答案:

答案 0 :(得分:2)

您错过了将文件指针分配给文件变量 试试这个

from datetime import datetime
ctime = str(datetime.now())
try:
    with open("pyth_log.txt", "w") as file:
        file.write("pyth_log.txt")
        file.write("-------")
        file.write("LOG")
        file.write(ctime)
        file.write("-------")
except:
    print("Unable to open file")

答案 1 :(得分:2)

from datetime import datetime

ctime = str(datetime.now())
try:
    with open("pyth_log.txt", "w") as file:
        file.write("-------\n")
        file.write("LOG\n")
        file.write(ctime)
        file.write("\n-------\n")
except:
    print("Unable to open file")
    raise

答案 2 :(得分:1)

要使用write()方法,必须使用文件对象。此外,最好使用with open()语法而不是调用close(),因为当with结束时,范围将被删除:

import datetime
from datetime import datetime
ctime = str(datetime.now())
try:
    with open("pyth_log.txt", 'w') as f:
        file.write("pyth_log.txt\n"
                   "-------\n"
                   "LOG\n"
                   + ctime + "\n"
                   "-------")
except:
    print("Unable to open file")
    raise