0

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.

Abhijeet
  • 1
  • 5
  • I think you may want to open the file with mode 'r+'. – John Anderson Dec 22 '18 at 02:57
  • Possible duplicate of [Prepend line to beginning of a file](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – Rish Dec 22 '18 at 03:05
  • Sir, I use code from that example still problem wasn't solved, so I put again here. Otherwise why should I do that. – Abhijeet Dec 22 '18 at 03:09

2 Answers2

0

I have tried below code snippet and its worked for me.

>>> with open("testfile","r+") as f:
...     lines = f.read()
...     f.seek(0)
...     f.write("back to line number 1 ")
...     f.write(lines)
...

Hope it helps.

Raja G
  • 5,973
  • 14
  • 49
  • 82
0
In [1]: file_name = "abc.txt"
   ...: open(file_name, "w").write("title\ndate\nsoap 10 1000 56 3 7\nsheets 34 2000 34 2 8\n")
   ...: 
   ...: !cat $file_name
title
date
soap 10 1000 56 3 7
sheets 34 2000 34 2 8

In [2]: f = open(file_name, "r").read().splitlines()
   ...: mean = 44
   ...: open(file_name, "w").write('\n'.join(['mean  ' + str(mean)]+f))
   ...: !cat $file_name
mean  44
title
date
soap 10 1000 56 3 7
sheets 34 2000 34 2 8

Amir saleem
  • 1,404
  • 1
  • 8
  • 11
  • It helps if you add some description of how you solved the problem and what was the problem in the code of the poster. – Ashi Nov 29 '20 at 13:53