Writing On The Topmost Row Of A Csv File
I have this sample.csv file: a 1 apple b 2 banana c 3 cranberry d 4 durian e 5 eggplant And have the following code: samplefile = open(sample.csv,'rb') rows =
Solution 1:
If you want to add to the end of the file(append to it):
withopen("sample.csv", "a") as fp:
fp.write("new text")
If you want to overwrite the file:
withopen("sample.csv", "w") as fp:
fp.write("new text")
If you want to remove a line from file:
import fileinput
import sys
for line_number, line inenumerate(fileinput.input('myFile', inplace=1)):
if line_number == 0: #first linecontinueelse:
sys.stdout.write(line)
If you want to add a new first line(before the existing one):
withopen("sample.csv", "r+") as fp:
existing=fp.read()
fp.seek(0) #point to first line
fp.write("new text"+existing) # add a line above the previously exiting first line
Post a Comment for "Writing On The Topmost Row Of A Csv File"