English 中文(简体)
开始档案的预支线
原标题:Prepend line to beginning of a file
  • 时间:2011-05-06 16:56:31
  •  标签:
  • python

我可以使用单独档案这样做,但我如何把一线连接到档案的开始?

f=open( log.txt , a )
f.seek(0) #get to the first position
f.write("text")
f.close()

这从档案的结尾开始,因为档案以传译方式开启。

最佳回答

在<方式代码> a 或 a+上,任何书面材料均在文档末尾,即便在目前<代码>write(<>>功能启动时,档案查询人不在档案的末尾:在任何书面材料之前,该查询人已移至卷宗的末尾。 你可以以两种方式做你们想要的东西。

1st way, 如无问题将档案装上记忆:

def line_prepender(filename, line):
    with open(filename,  r+ ) as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip( 
 ) +  
  + content)

<>2nd way:

def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print line_to_prepend.rstrip( 
 ) +  
  + xline,
        else:
            print xline,

我不知道这种方法如何在一生中发挥作用,能否在大档案中加以使用。 提交意见的第1论点是能够重写一条线的;为了开展地方行动,必须向前推进或后退,但我不知道这一机制。

问题回答

在我所熟悉的所有档案系统中,你无法做到这一点。 你必须使用辅助档案(然后可以改名取原始档案的名称)。

为了向国家扫盲委员会提出答案,我认为最有效的办法是:

def insert(originalfile,string):
    with open(originalfile, r ) as f:
        with open( newfile.txt , w ) as f2: 
            f2.write(string)
            f2.write(f.read())
    os.remove(originalfile)
    os.rename( newfile.txt ,originalfile)

不同的想法:

(1) 你将原始档案作为变量予以保存。

(2) 你用新信息推翻原始档案。

(3) 你在数据库中附上新资料。

法典:

with open(<filename>, r ) as contents:
      save = contents.read()
with open(<filename>, w ) as contents:
      contents.write(< New Information >)
with open(<filename>, a ) as contents:
      contents.write(save)

如果你不想再次书写档案,那么这样做的明确方式如下:

with open("a.txt",  r+ ) as fp:
    lines = fp.readlines()     # lines is list of line, each element  ...
 
    lines.insert(0, one_line)  # you can use any index if you know the line index
    fp.seek(0)                 # file pointer locates at the beginning to write the whole file again
    fp.writelines(lines)       # write whole lists again to the same file

请注意,这不是替代。 它再次撰写档案。

简言之,你读到一份档案,将其保存到一份清单中,并修改名单,再次将名单写到一份新档案中,并附上相同的档案。

num = [1, 2, 3] #List containing Integers

with open("ex3.txt",  r+ ) as file:
    readcontent = file.read()  # store the read value of exe.txt into 
                                # readcontent 
    file.seek(0, 0) #Takes the cursor to top line
    for i in num:         # writing content of list One by One.
        file.write(str(i) + "
") #convert int to str since write() deals 
                                   # with str
    file.write(readcontent) #after content of string are written, I return 
                             #back content that were in the file

任何内在职能都无法做到这一点,因为这将非常低效率。 每次在前面添加一条线时,你必须改变档案的现有内容。

可在文档结尾处读出的“Unix/article tail

with open("fruits.txt", "r+") as file:
    file.write("bab111y")
    file.seek(0)
    content = file.read()
    print(content)

如果档案太大,无法作为清单使用,而且你只是想推翻档案,那么,你可以先以倒置的次序书写档案,然后在档案结束时读到一条线(并写到另一个档案),备案模块。

对现有解决办法的改进如下:

def prepend_text(filename: Union[str, Path], text: str):
    with fileinput.input(filename, inplace=True) as file:
        for line in file:
            if file.isfirstline():
                print(text)
            print(line, end="")

它被打上了型号,更能读取,近年来使用一些改进标准,如环境主管:

我尝试了另一种做法:

I wrote first line into a header.csv file. body.csv was the second file. Used Windows type command to concatenate them one by one into final.csv.

import os

os.system( type c:\header.csv c:\ody.csv > c:\final.csv )




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...