I have 200 text files that contains 133 lines (first one is the header) and 9 columns each. What I am trying to do is to multiply all the values of the E-Amp and N-amp columns by 10, and replace the old values by the new ones in the same file, and save in the same format. Here's an example of one of the files:
Extension/Epoch Lat( N,deg) Lon( E,deg) E-Amp(mm) E-Pha(deg) N-Amp(mm) N-Pha(deg) V-Amp(mm) V-Pha(deg)
20080101000000 36.87500000 329.50000000 3.46453912 0.00000000 6.56776394 180.00000000 7.15208982 180.00000000
20080201000000 36.87500000 329.50000000 0.30411436 180.00000000 5.06292797 180.00000000 3.16756356 180.00000000
20080301000000 36.87500000 329.50000000 1.93205829 0.00000000 0.25084443 0.00000000 2.88015036 180.00000000
20080401000000 36.87500000 329.50000000 0.64129867 0.00000000 2.28822012 0.00000000 2.87279715 180.00000000
20080501000000 36.87500000 329.50000000 1.79042810 180.00000000 5.02766918 0.00000000 6.21064019 0.00000000
20080601000000 36.87500000 329.50000000 2.05377778 180.00000000 5.67777792 0.00000000 11.62667229 0.00000000
20080701000000 36.87500000 329.50000000 4.23575230 180.00000000 5.90637626 0.00000000 10.19361807 0.00000000
20080801000000 36.87500000 329.50000000 2.68562850 180.00000000 5.30434018 0.00000000 8.97660361 0.00000000
I tried to do the following:
path = 'C:/Users/User/.../folder'
file_list = glob.glob(path '*.txt')
for file in file_list:
date = np.loadtxt(file,usecols=(0,),dtype='U',unpack=True,skiprows=1)
lat,lon,eamp,epha,namp,npha,vamp,vpha = np.loadtxt(file,delimiter=None,unpack=True,skiprows=1,usecols=(1,2,3,4,5,6,7,8))
eamp=eamp*10
namp=namp*10
But I have no ideia how to replace the values and save in the same file. I tried this > How to change just one column in a txt file leaving all else the same and respecting the whitespaces? but it didn't work.
Any help, pls?
CodePudding user response:
lines = []
#Read the file and save in memory
with open('file.txt', 'r') as f:
for line in f:
lines.append(line.split())
#Do the modification
is_first_line = True
for line in lines:
if is_first_line:
is_first_line = False
continue
line[3] = str(10*float(line[3]))
line[5] = str(10*float(line[5]))
#Rewrite the file with the modification
with open('file.txt', 'w') as f:
for line in lines:
print(" ".join(line), file=f)
CodePudding user response:
#update. Doing for the 200 files:
path1='C:/Users/User/.../folder/'
path2='C:/Users/User/.../output_folder/'
liist = os.listdir(path1)
for i in range(len(liist)):
lines = []
#Read the file and save in memory
with open(path1 liist[i], 'r') as f:
for line in f:
lines.append(line.split())
#Do the modification
is_first_line = True
for line in lines:
if is_first_line:
is_first_line = False
continue
line[3] = str(10*float(line[3]))
line[5] = str(10*float(line[5]))
#Rewrite the file with the modification
with open(path2 liist[i], 'w') as f: #put the modified files in a new folder (path2)
for line in lines:
print(" ".join(line), file=f)