需要帮助解决错误“ TypeError:'NoneType'对象不可下标”

时间:2019-07-12 01:41:35

标签: python

我是python的新手,正在做一些小任务,遇到了一些麻烦。我想知道如何将附加到文件的底部空白行。

该代码已经打印出“ .txt”中的内容,并且“ cnt”作为下一行显示,其中没有文本。

#Open the desired file
f = open("Testing.txt", "r")

#Read out lines of the file and number them
line = f.readline()
cnt = 1
while line:
    print("Line {}: {}".format(cnt, line.strip()))
    line = f.readline()
    cnt += 1
print("Line {}: {}".format(cnt, newline))
f.close()

#Append new line to bottom of file
f = open("Computers.cfg", "a")
f.writelines(newline)[cnt]
f.close()

如果文件读取类似

Hello
I am
here

我想在底行添加“现在”,以便显示为

Hello
I am
here
now

我是否正在正确处理此问题,或者有更好或更干净的方法来做到这一点?

2 个答案:

答案 0 :(得分:0)

这是我的解决方案,我将事情简化了很多。看看这是否适合您。

#Open the desired file
f = open("Testing.txt", "r")
text = f.read()

if text[-1] != '\n':
    newline = '\n'+newline

f.close()

#Append new line to bottom of file
n = open("Computers.cfg", "w")
n.write(text+newline)
n.close()

答案 1 :(得分:0)

“ TypeError:'NoneType'对象不可下标”是Python错误之一,无法为新开发人员提供明确的答案。

这意味着您正在尝试在不支持此操作的对象上使用下标(或索引)运算符[]

之所以引用NoneType是因为File.writelines()的响应是None

将所有这些放在一起,您正尝试在f.writelines(newline)[cnt]行上索引为None。

将此行更改为f.write("\nnow")将解决此问题(“ \ n”是换行符的简称)。