简体   繁体   English

如何在python中替换文件中的特定值

[英]How do i replace a specific value in a file in python

Im trying to replace the zero's with a value. 我试图用一个值替换零。 So far this is my code, but what do i do next? 到目前为止,这是我的代码,但是我下一步该怎么做?

g = open("January.txt", "r+")
for i in range(3):
        dat_month = g.readline()

Month: January
Item: Lawn
Total square metres purchased:
0
monthly value = 0
dat_month = dat_month.replace("0", "45678")

To write to a file you do: 要写入文件,请执行以下操作:

with open("Outfile.txt", "wt") as outfile:

And then 接着

outfile.write(dat_month)

You could do that - but that is not the usual approach, and certainly is not the correct approach for text files. 可以执行此操作-但这不是通常的方法,而且对于文本文件来说当然不是正确的方法。

The correct way to do it is to write another file, with the information you want updated in place, and then rename the new file to the old one. 正确的方法是编写另一个文件,其中要更新的信息就位,然后将新文件重命名为旧文件。 That is the only sane way of doing this with text files, since the information size in bytes for the fields is variable. 这是对文本文件执行此操作的唯一明智的方法,因为字段的字节信息大小是可变的。

As for the impresion that you are "writing 200 bytes to the disk" instead of a single byte, changing your value, don't let that fool you: at the Operating system level, all file access has to be done in blocks, which are usually a couple of kilobytes long (in special cases, and tunned filesystems it could be a couple hundred bytes). 至于您正在“将200个字节写入磁盘”而不是单个字节这种隐含的印象,改变了您的值,请不要愚弄您:在操作系统级别,所有文件访问都必须以块的形式进行,这通常是几千字节长(在特殊情况下,调整后的文件系统可能是几百字节)。 Anyway, you will never, in a user-space program, much less in a high level language like Python, trigger a diskwrite of less than a few hundred bytes. 无论如何,在用户空间程序中,绝不会像Python这样的高级语言触发磁盘写入少于几百个字节的情况。

Now, for the code: 现在,对于代码:

import os
my_number = <number you want to place in the line you want to rewrite>
with open("January.txt", "r") as in_file, open("newfile.txt", "w") as out_file:

    for line in in_file:
        if line.strip() == "0":
             out_file.write(str(my_number) + "\n")
        else:
             out_file.write(line)

os.unlink("January.txt")
os.rename("newfile.txt", "January.txt")

So - that is the general idea - of course you should not write code with all values hardcoded in that way (ie the values to be checked and written fixed in the program code, as are the filenames). 所以-这是一个普遍的想法-当然,您不应该编写带有以这种方式硬编码的所有值的代码(即,要检查和写入的值固定在程序代码中,文件名也是如此)。

As for the with statement - it is a special construct of the language wich is very appropriate to oppening files and manipulating then in a block, like in this case - but it is not needed . 至于with语句-这是一种特殊的语言构造,非常适合于处理文件并随后在一个块中进行操作(例如在这种情况下)-但这不是必需的

Programing apart, the concept you have to keep in mind is this: when you use an application that lets you edit a text file, a spreadsheet, an image, you, as user, may have the impression that after you are done and have saved your work, the updates are comitted to the same file . 分开编程,您必须牢记的概念是:当您使用允许您编辑文本文件,电子表格,图像的应用程序时,您作为用户可能会觉得在完成并保存后您的工作将更新提交到同一文件 In the vast, vast majority of use cases, that is not what happens : the application uses internally a pattern like the one I presented above - a completly new file is written to disk and the old one is deleted, or renamed. 在绝大多数用例中, 情况并非如此 :应用程序内部使用一种模式,如我上面介绍的那样-将一个完全新的文件写入磁盘,然后删除或重命名一个旧文件 The few exceptions could be simple database applications, which could replace fixed width fields inside the file itself on updates. 少数例外可能是简单的数据库应用程序,可以在更新时替换文件本身内部的固定宽度字段。 Modern day databases certainly do not do that, resorting to appending the most recent, updated information, to the end of the file. 现代数据库肯定不会这样做,而是将最新的更新信息附加到文件末尾。 PDF files are another kind that were not designed to be replaced entirely on each update, when being created: but also in that case, the updated information is written at the end of the file, even if the update is to take place in a page in the beginning of the rendered document. PDF文件是另一种,并非在创建时就打算在每次更新时都完全替换掉;但是在这种情况下,即使更新要在页面中进行,更新后的信息也会写在文件末尾。在呈现文档的开头。

Try this: 尝试这个:

import fileinput
import itertools
import sys
with fileinput.input('January.txt', inplace=True) as file:
    beginning = tuple(itertools.islice(file, 3))
    sys.stdout.writelines(beginning)
    sys.stdout.write(next(file).replace('0', 'a value'))
    sys.stdout.write(next(file).replace('0', 'a value'))
    sys.stdout.writelines(file)

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

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