Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write in txt
#1
Here is a code i wrote to find max value and its location in n number of file
I can print them in screen but dont know hoe to write them in a txt file. Could u help me

from numpy import loadtxt
from numpy import max as max2
from os import listdir, chdir, getcwd
from matplotlib.pylab import where

# accesing to folder with hmax_00001 ...
chdir('hmax')

# obtain files list
file1 = listdir(getcwd())
# obtain number of files
n = len(file1)

# read files, one by one
for i in range(n):
    # load file
    d1 = loadtxt(file1[i])    
    # calculate max value
    h1max = max2(d1)
    # search position of max value
    px, py = where(h1max==d1)    
    # show data in screen 
    print (file1[i],'Max = ',h1max,' loc = (',px[0],',',py[0],')')    
    # delete variables 
    del d1, h1max, px, py
del i

# return to folder initial
chdir('..')
Reply
#2
Writing something in a text file is simple. You can use pickle to kind of encode the data -
import pickle

file = open('file.txt', 'wb') #'wb' means write bytes
pickle.dump(file, variable) #dump means to save it in there
file.close()

file = open('file.txt', 'rb') #"rb" means read bytes
variable = pickle.load(file)

Hopes this helps
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020