0

我有一个这样的文本文件:-

V1xx AB1
V2xx AC34
V3xx AB1

我们可以;通过python脚本在每一行添加吗?

V1xx AB1;
V2xx AC34;
V3xx AB1;
4

3 回答 3

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() + ";"
于 2012-10-16T22:35:13.633 回答
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')
于 2012-10-16T22:40:10.390 回答
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 模块)

于 2012-10-16T22:34:08.287 回答