例如,我有一个带有以下文本的文件:
Hello
One
two
Goodbye
我想在“两个”和“再见”之间添加“三个”
我该怎么做?
答案 0 :(得分:-1)
首先,您应该阅读文件内容:(假设您的文件与.py文件位于同一文件夹中)
name = "YOUR FILE NAME" # including extension, such as "myfile.txt"
data = []
filename = os.path.abspath(os.path.join(name))
if os.path.exists(filename):
with open(filename) as fin:
for entry in fin.readlines():
data.append(entry.rstrip())
应在数据数组中插入另一个元素(在本例中为索引3)
data.insert(3, "three")
最后,只需使用以下新信息保存文件:
with open(filename, 'w') as fout:
for entry in data:
fout.write(entry + '\n')