我试图修改txt文件。该文件是格式为
的电影脚本BEN We’ve discussed this before.
LUKE I can be a Jedi. I’m ready.
我想在角色后插入一个新行:
BEN
We’ve discussed this before.
LUKE
I can be a Jedi. I’m ready.
我如何在python中执行此操作?我目前有:
def modify_file(file_name):
fh=fileinput.input(file_name,inplace=True)
for line in fh:
split_line = line.split()
if(len(split_line)>0):
first_word = split_line[0]
replacement = first_word+'\n'
first_word=first_word.replace(first_word,replacement)
sys.stdout.write(first_word)
fh.close()
答案 0 :(得分:2)
根据其中一条评论中的建议,可以使用split
和isupper
来完成此操作。下面提供了一个示例:
source_path = 'source_path.txt'
f = open(source_path)
lines = f.readlines()
f.close()
temp = ''
for line in lines:
words = line.split(' ')
if words[0].isupper():
temp += words[0] + '\n' + ' '.join(words[1:])
else:
temp += line
f = open(source_path, 'w')
f.write(temp)
f.close()
答案 1 :(得分:0)
您的代码存在多个问题。
import fileinput
def modify_file(file_name):
fh=fileinput.input("output.txt",inplace=True)
for line in fh:
split_line = line.split()
if(len(split_line)>0):
x=split_line[0]+"\n"+" ".join(split_line[1:])+"\n"
sys.stdout.write(x)
fh.close() #==>this cannot be in the if loop.It has to be at the outer for level