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?

Find Min/max for X and Y, then interpolate for 5000 txt files with python
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)



