简体   繁体   English

如何通过在中间插入/更改字符来修改文本文件?

[英]How to modify a text file by inserting/changing characters in the middle?

I'm trying to write a code that modifies certain text in a text file.我正在尝试编写一个修改文本文件中某些文本的代码。 I want it to write to a different file not append the old file.我希望它写入另一个文件而不是 append 旧文件。 The.replace function does not work because I'm not replacing a certain word with another word. The.replace function 不起作用,因为我没有用另一个词替换某个词。 I'm doing math operations to a certain part of the file, then I want the new file to contain the new information.我正在对文件的某个部分进行数学运算,然后我希望新文件包含新信息。

I tried reading each line, looping through the lines and writing the code I want by slicing the line, but its not working.我尝试阅读每一行,遍历这些行并通过切片来编写我想要的代码,但它不起作用。 The code does not change anything in the text file.该代码不会更改文本文件中的任何内容。

This is the code:这是代码:

filename = "timetag.txt"
fileout = "converted_timetag.txt"

old = open(filename,'r')
lines = old.readlines()
new = open(fileout,'w')

for line in lines:
    time = int(line[6:15])*20
    newlines = [str(line[:6]) + str(time) + "\n"]
    new.write(newlines)

old.close()
new.close()

In the line newlines = [str(line[:6]) + str(time) + "\n"] you use the [ ] , which attempts to make newlines into a list .newlines = [str(line[:6]) + str(time) + "\n"]行中,您使用[ ] ,它试图将换行符变成list This gives an error during runtime,这会在运行时出错,

TypeError: write() argument must be str, not list TypeError: write() 参数必须是 str,而不是 list

Since new.write(newlines) needs to take a string, not a list.由于new.write(newlines)需要一个字符串,而不是一个列表。

You can fix this error by taking out the square brackets, like so: newlines = str(line[:6]) + str(time) + "\n" .您可以通过去掉方括号来修复此错误,如下所示: newlines = str(line[:6]) + str(time) + "\n"

Your code would look like:您的代码如下所示:

filename = "timetag.txt"
fileout = "converted_timetag.txt"

old = open(filename,'r')
lines = old.readlines()
new = open(fileout,'w')

for line in lines:
    time = int(line[6:15])*20
    newlines = str(line[:6]) + str(time) + "\n"
    new.write(newlines)

old.close()
new.close()

If timetag.txt contains:如果 timetag.txt 包含:

time: 123456789
time: 100000000
time: 000000001
time: 000000002

The output is: output 是:

time: 2469135780
time: 2000000000
time: 20
time: 40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM