I wanted to write a result getting from code, to same name existing file in other directory "/home/work/new_data/ " at first line. My file names are abc.1 to abc.1000
I tried as following but I didn't get output as expected, is it due to myfile contains "." character or something else I was missing? (my file is little bigger)
import pandas as pd
import numpy as np
import re
import glob
for filename in sorted(glob.glob('abc.*')):
with open(filename) as f:
df = pd.read_table(f, sep=" ", skiprows=2, names = ["Name" , "price", "quntity", "avg_q", "kke", "te"])
mean = np.mean(df.price)
name = (re.sub('[^0-9]','' , filename)) . #extracting the number from filename
#NOW I TRIED FOLLOWING TO write mean at first line of existing file
with open ("/home/work/new_data/abc.(name)", "rw") as new:
lines = new.readlines() # read old content
new.seek(0) # go back to the beginning of the file
new.write('{}'.format(mean)) # write new content at the beginning
for line in lines: # write old content after new
new.write(line)
new.close()
I want abc.1 to be
mean #got from program output
title
date
soap 10 1000 56 3 7
sheets 34 2000 34 2 8
...
My actual file which I was processing abc.1:
title
date
soap 10 1000 56 3 7
sheets 34 2000 34 2 8
...
I refer Prepend line to beginning of a file still problem doesn't solved.