Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to write to a specific line in a file python

with open('input') as fin, open('output','w') as fout:
    for line in fin:
        fout.write(line)
        if line == 'xxxxx
':
           next_line = next(fin)
           if next_line == 'yyyyy
':
              fout.write('my_line
')
           fout.write(next_line)
           
Comment

python write a line to a file

f=open('output.txt', 'w')
print("Hello world", file=f)
f.close
Comment

how to write to a specific line in a file python

# An alternate approach would be to write a function to yield lines until it sees an xxxxx
yyyyy

def getlines(fobj,line1,line2):
     for line in iter(fobj.readline,''):  #This is necessary to get `fobj.tell` to work
         yield line
         if line == line1:
             pos = fobj.tell()
             next_line = next(fobj):
             fobj.seek(pos)
             if next_line == line2:
                 return
# Then you can use this passed directly to writelines:
with open('input') as fin, open('output','w') as fout:
    fout.writelines(getlines(fin,'xxxxx
','yyyyy
'))
    fout.write('my_line
')
    fout.writelines(fin)
                
Comment

PREVIOUS NEXT
Code Example
Python :: matplotlib savefig legend cut off 
Python :: beautifulsoup find element by partial text 
Python :: rename column in pandas with second row 
Python :: python max function recursive 
Python :: python index max list 
Python :: python plot horizontal line 
Python :: numpy.random.choice 
Python :: how to iterate over a list in python 
Python :: flask flash 
Python :: python remove common elements between two lists 
Python :: remove na python 
Python :: python endwith 
Python :: make int into string python 
Python :: pandas do not display index 
Python :: python change directory to previous 
Python :: standardscaler 
Python :: driver find element with multiple classes python 
Python :: encryption using python 
Python :: django convert object to dict 
Python :: format column from string to numeric in python 
Python :: how to declare np datetime 
Python :: pandas reset index from 0 
Python :: python dataframe replace in all dataframe 
Python :: pandas replace nan with value above 
Python :: plotly pie chart in pie chart 
Python :: python spliting string into list 
Python :: np.tanh 
Python :: lambda en python 
Python :: image resize in python 
Python :: how to remove time in datetime in python 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =