你可以try creating a new one(我留给你)-你需要稍微修改一下你的with语句:-
lines = ""
with open('D:\File.txt') as file:
for line in file:
lines += line.strip() + ";\n"
file = open('D:\File.txt', "w+")
file.writelines(lines)
file.flush()
更新:-对于文件的就地修改,可以使用fileinput模块:-
import fileinput
for line in fileinput.input('D:\File.txt', inplace = True):
print line.strip() + ";"
#Open the original file, and create a blank file in write mode
File = open("D:\myfilepath\myfile.txt")
FileCopy = open("D:\myfilepath\myfile_Copy.txt","w")
#For each line in the file, remove the end line character,
#insert a semicolon, and then add a new end line character.
#copy these lines into the blank file
for line in File:
CleanLine=line.strip("\n")
FileCopy.write(CleanLine+";\n")
FileCopy.close()
File.close()
#Replace the original file with the copied file
File = open("D:\myfilepath\myfile.txt","w")
FileCopy = open("D:\myfilepath\myfile_Copy.txt")
for line in FileCopy:
File.write(line)
FileCopy.close()
File.close()
input_file_name = 'input.txt'
output_file_name = 'output.txt'
with open(input_file_name, 'rt') as input, open(output_file_name, 'wt') as output:
for line in input:
output.write(line[:-1]+';\n')
你可以试试看。不过我有
overwritten the same file
。你知道吗你可以
try creating a new one
(我留给你)-你需要稍微修改一下你的with
语句:-更新:-对于文件的就地修改,可以使用
fileinput
模块:-注意:我把“拷贝文件”放在那里作为备份。您可以手动删除或使用os.删除()(如果这样做,请不要忘记导入操作系统模块)
相关问题 更多 >
编程相关推荐