I didn’t want to get too off-topic, but yeah, that’s a good start—though it could really use some further refinements. I would suggest the following high-level approach:
- Store your input data into a data structure, such as a dictionary, instead of individual variables
- Use a for loop over the “database” keys to ask the user to input each one, and insert them into the dictionary
- Use a comprehension (or for loop) to construct each line of the text file, then
jointhem together with newlines - Open the file in a
withblock with the correct encoding, and write the whole thing in one go - Finally, create the dataframe directly from the dictionary
Here’s what this looks like, with comments explaining each part:
import pandas as pd
# Step 0: Create a dictionary in which to store the user data
input_data = {}
# Step 1: Use a for loop to get and store the data for each field
for field_key in ["Name", "Surname", "Age", "Height", "YoB"]:
field_value = input(f"Enter {field_key}: ") # Use an f-string to insert the key
input_data[field_key] = field_value # Store the data for each field in the dict
# Step 2: Convert the data to the desired text file output string
# This uses a list comprehension, like a for loop but in a single expression
# To build a list of key: value lines in the output text file content
output_lines = [f"{key}: {value}" for key, value in input_data.items()]
output_text = "\n".join(output_lines) # Join the lines into a string w/newlines
# Step 3: Write the file all in one go
# This uses a with statement, to open & close the file safety and automatically
# And the correct UTF-8 encoding, otherwise it won't work with non-English names
with open("data_base.txt", "w", encoding="UTF-8") as out_file:
out_file.write(output_text)
# Step 4: Create the dataframe directly from the dictionary
df = pd.DataFrame([input_data])
Now, if you need to add an additional key, change the key names or add more users, you only need to change one line of the code and everything will work. Plus, its much shorter and simpler for you to read.