How do I write to the middle of a text file while reading its contents?

前端 未结 3 1445
时光取名叫无心
时光取名叫无心 2020-12-06 22:03

First of all thanks for helping me out with moving files and for helping me in with tcl script.

Small doubt i had with python code.. as below..

impor         


        
相关标签:
3条回答
  • 2020-12-06 22:33

    Actually your method works but your fout is open in append mode. So this is why you can only write at the end. Here is an working example.

    # creating a file for reference
    ff = open("infiletest","w")
    pos_file = {}
    for i in range(3):
        pos_file[i] = ff.tell()
        ff.write("%s   21/1/1983\n" % i)
    ff.close()
    
    # modify the second line
    ff = open("infiletest","r+")
    ff.seek(pos_file[2])
    ff.write("%s   00/0/0000\n" % 2)
    ff.close()
    

    Note that that you overwritte the content of the file.

    0 讨论(0)
  • 2020-12-06 22:42

    A simple way to add data in the middle of a file is to use fileinput module:

    import fileinput
    
    for line in fileinput.input(r'C:\Sanity_Automation\....tcl', inplace=1):
        print line, # preserve old content
        if x in line:
           print data # insert new data
    

    From the fileinput docs:

    Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed.

    To insert data into filename file while reading it without using fileinput:

    import os
    from tempfile import NamedTemporaryFile
    
    dirpath = os.path.dirname(filename)
    with open(filename) as file, \
         NamedTemporaryFile("w", dir=dirpath, delete=False) as outfile:
        for line in file:
            print >>outfile, line, # copy old content
            if x in line:
               print >>outfile, data # insert new data
    
    os.remove(filename) # rename() doesn't overwrite on Windows
    os.rename(outfile.name, filename)
    
    0 讨论(0)
  • 2020-12-06 22:43

    you dont all you can do is read in the file, insert the text you want, and write it back out

    with open("some_file","r") as f:
         data = f.read()
    some_index_you_want_to_insert_at = 122
    some_text_to_insert = "anything goes here"
    
    new_data = data[:some_index_you_want_to_insert_at] + some_text_to_insert + data[some_index_you_want_to_insert_at:]
    
    with open("some_file","w") as f:
         f.write(new_data)
    
    print "all done!"
    
    0 讨论(0)
提交回复
热议问题