我有一个这样的文本文件: -
V1xx AB1
V2xx AC34
V3xx AB1
我们可以通过python脚本在每一行添加;
吗?
V1xx AB1;
V2xx AC34;
V3xx AB1;
答案 0 :(得分:1)
这是你可以尝试的。我虽然有overwritten the same file
。
你可以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() + ";"
答案 1 :(得分:1)
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')
答案 2 :(得分:0)
#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()
注意:我已将“复制文件”留在那里作为备份。您可以手动删除它或使用os.remove()(如果这样做,请不要忘记导入os模块)