Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to replace first line of a textfile python

with open("test.txt") as f:
    lines = f.readlines()

lines # ['This is the first line.
', 'This is the second line.
']

lines[0] = "This is the line that's replaced.
"

lines # ["This is the line that's replaced.
", 'This is the second line.
']

with open("test.txt", "w") as f:
    f.writelines(lines)
Comment

PREVIOUS NEXT
Code Example
Python :: python convert list to absolute value 
Python :: python program for printing fibonacci numbers 
Python :: falsy values in python 
Python :: tkinter open new window 
Python :: pytest check exception 
Python :: Substring in a django template? 
Python :: numpy standard deviation 
Python :: Adding new column to existing DataFrame in Pandas by assigning a list 
Python :: how to read tuples inside lists python 
Python :: python super init 
Python :: how to enable execution time in jupyter lab 
Python :: django drop database postgres 
Python :: how to add three conditions in np.where in pandas dataframe 
Python :: catch error python 
Python :: Insert missing data in pandas 
Python :: remove duplicates python 
Python :: count rows with nan pandas 
Python :: find null values pandas 
Python :: python naming conventions 
Python :: python remove last element from list 
Python :: np.zeros data type not understood 
Python :: n-largest and n-smallest in list in python 
Python :: django query field is null 
Python :: how to convert gb to mb in python 
Python :: python sizeof 
Python :: second y axis matplotlib 
Python :: pyspark when otherwise multiple conditions 
Python :: create close python program in puthon 
Python :: accessing index of dataframe python 
Python :: python scanner class 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =