更改输出文本的格式

2024-07-03 07:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件本文件:你知道吗

V1xx AB1
V2xx AC34
V3xx AB1

我们可以通过python脚本在每一行的末尾添加;吗?你知道吗

V1xx AB1;
V2xx AC34;
V3xx AB1;

Tags: 文件脚本文本文件末尾ab1v3xxv1xxac34
3条回答

你可以试试看。不过我有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() + ";"
#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.删除()(如果这样做,请不要忘记导入操作系统模块)

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')

相关问题 更多 >