set waw filename from file text in python

To set a file name in Python from a file text, you can use the os module to manipulate the file path and string manipulation functions to extract the file name from the file text.

Here is an example code snippet that demonstrates how to read a file, extract the first line as the file name, and then use it to create a new file with that name:

main.py
import os

# open the file for reading
with open("file.txt", "r") as file:
    # read the first line for the file name
    filename = file.readline().strip()

# create a new file using the extracted file name
with open(os.path.join("path/to/save", filename), "w") as new_file:
    # write something to the new file
    new_file.write("Hello, world!")
351 chars
12 lines

In this example, we first open the file "file.txt" for reading using a with statement to ensure that the file is properly closed after we are done with it.

Next, we read the first line of the file using the readline method and use the strip method to remove any leading or trailing whitespace from the line.

We then use the os.path.join method to combine the directory where we want to save the new file with the extracted file name to create a complete file path. Finally, we open the new file for writing using a with statement and the "w" mode, and write something to it.

gistlibby LogSnag