简体   繁体   English

在python中更改文件的第一行

[英]change first line of a file in python

I only need to read the first line of a huge file and change it.我只需要读取一个大文件的第一行并更改它。

Is there a trick to only change the first line of a file and save it as another file using Python?有没有一种技巧可以只更改文件的第一行并使用 Python 将其另存为另一个文件? All my code is done in Python and would help me to keep consistency.我所有的代码都是用 Python 完成的,这会帮助我保持一致性。

The idea is to not have to read and then write the whole file.这个想法是不必读取然后写入整个文件。

shutil.copyfileobj() should be much faster than running line-by-line. shutil.copyfileobj()应该比逐行运行快得多。 Note from the docs:文档中的注释:

Note that if the current file position of the [from_file] object is not 0, only the contents from the current file position to the end of the file will be copied.注意,如果[from_file]对象的当前文件位置不为0,则只会复制从当前文件位置到文件末尾的内容。

Thus:因此:

from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

If you want to modify the top line of a file and save it under a new file name, it is not possible to simply modify the first line without iterating over the entire file.如果要修改文件的第一行并将其保存在新文件名下,则不可能在不遍历整个文件的情况下简单地修改第一行。 On the bright side, as long as you are not printing to the terminal, modifying the first line of a file is VERY, VERY fast even on vasy large files.从好的方面来说,只要你不打印到终端,修改文件的第一行是非常非常快的,即使是在大文件上也是如此。

Assuming you are working with text-based files (not binary,) this should fit your needs and perform well enough for most applications.假设您正在使用基于文本的文件(不是二进制文件),这应该符合您的需求并且对于大多数应用程序来说性能足够好。

import os
newline = os.linesep # Defines the newline based on your OS.

source_fp = open('source-filename', 'r')
target_fp = open('target-filename', 'w')
first_row = True
for row in source_fp:
    if first_row:
        row = 'the first row now says this.'
        first_row = False
    target_fp.write(row + newline)

An alternate solution that does not require iterating over the lines that are not of interest.不需要迭代不感兴趣的行的替代解决方案。

def replace_first_line( src_filename, target_filename, replacement_line):
    f = open(src_filename)
    first_line, remainder = f.readline(), f.read()
    t = open(target_filename,"w")
    t.write(replacement_line + "\n")
    t.write(remainder)
    t.close()

Unless the new line is the same length as the old line, you can not do this.除非新行与旧行的长度相同,否则您不能这样做。 If it is, you could solve this problem through a mmap .如果是,您可以通过mmap解决此问题。

The sh module worked for me: sh模块对我sh

import sh

first = "new string"
sh.sed("-i", "1s/.*/" + first + "/", "file.x")

The solution i would use is to use create a file missing old first line我将使用的解决方案是使用创建一个缺少旧第一行的文件

from_file.readline() # and discard shutil.copyfileobj(from_file, tail_file)

then create a file with the new first line然后用新的第一行创建一个文件

then use the following to concatenate the newfirstline file and tail_file然后使用以下内容连接 newfirstline 文件和 tail_file

for f in ['newfirstline.txt','tail_file.txt']:
with open(f,'rb') as fd:
    shutil.copyfileobj(fd, wfd, 1024*1024*10

Here is the working example of "Nacho" answer:这是“Nacho”答案的工作示例:

import subprocess

cmd = ['sed', '-i', '-e', '1,1s/.*/' + new_line + '/g', 'filename.txt']

subprocess.call(cmd)

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

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