0

In this post I have asked how to select files in a directory by using a number as index. Now I would like to save this file in an automatic way, without adding manually the name. For example:

I have the following list, generated by the code (as suggested by Eric M):

files = [f for f in glob.glob("*.txt")]

for fi, f in enumerate(files):
    print(fi, f)

query = input("Please add your selection: ") # just the number
df = pd.read_csv(files[int(query)])

Output:

1     text1.txt
2     text2.txt
3     text3.txt
...

After some changes in the dataframe, I would like to save the new table into a new file, e.g.

text1_test.txt

or

text2_test.txt

However, to do this I would need to get back information about the number that I selected in the code above, i.e. by query.

How could I do that?

1 Answer 1

1

This one solution there can be many. When you read the dataframe, save the name of the file as the name of the index and later you can use this variable in case query no longer is available:

df = pd.read_csv(files[int(query)])
df.index.name = files[int(query)]

# Do other stuff

csv_name = df.index.name.split('.')[0] + '_test.txt'
df.to_csv(csv_name)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.