-3

I have this working code to process a single file:

import pandas as pd
import pygmt

#import table
df = pd.read_table("file1.txt", sep=" ", names=['X', 'Y', 'Z'] ) 

#min/max
Xmin = df['X'].min()
Xmax = df['X'].max()
Ymin = df['Y'].min()
Ymax = df['Y'].max()
#print(Xmin, Xmax)
#print(Ymin, Ymax)

#gridding with pyGMT
grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax]) 

#print(grid) 
#export
grid.to_netcdf('file1.nc') 

Now I want to repeat this code for all *.txt files in a directory. How can I do that? I tried writing a loop like:

for file in glob.glob("*.txt"):

But how can I make the respective input (.txt) and output (.nc) have the same name?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
frivo
  • 17
  • 4
  • "But how do i manage that the respective input (.txt). and output (.nc) have the same name?" - **what exactly does this mean**? Think carefully, step by step, about what need to happen. **When you tried using** your loop (`for file in glob.glob("*.txt"):`), **what values** did you see for `file` inside the loop? That tells you the name of the input file, right? **What steps need to be taken** in order to compute the output file name? If you know how to do those steps, is there still a problem beyond that? – Karl Knechtel Jun 02 '23 at 07:37
  • As an aside, please read [ask] and note well that this is **not a discussion forum**. Please do not tell us in the question about your level of experience or the overall context of your project (any more than is **required to understand the question**), and do not sign the question or offer thanks. **Just ask the question, please**. I have edited to show what it should look like. – Karl Knechtel Jun 02 '23 at 07:41

1 Answers1

0

As said before in comment section you also can do it by iterating all .txt filenames and changes their formats to .nc with saving names.

import glob
import pandas as pd
import pygmt

filenames_in = glob.glob("*.txt")

for filename_in in filenames_in:
    filename_out = filename_in.replace('.txt', '.nc')
    # YOUR CODE
    # import table
    df = pd.read_table(filename_in, sep=" ", names=['X', 'Y', 'Z'])

    # min/max
    Xmin = df['X'].min()
    Xmax = df['X'].max()
    Ymin = df['Y'].min()
    Ymax = df['Y'].max()
    # print(Xmin, Xmax)
    # print(Ymin, Ymax)

    # gridding with pyGMT
    grid = pygmt.surface(data=df, spacing=1, region=[Xmin, Xmax, Ymin, Ymax])

    # print(grid)
    # export
    grid.to_netcdf(filename_out)


MrMarvel
  • 34
  • 5