World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
How can I convert an unformatted text file list into a Python list in another file?
To convert a list of items from an unformatted text file to a Python list in a separate file, you can use the following method:
1. Open the unformatted text file using the open() function in Python, and specify the file mode as 'r' (read).
with open('input.txt', 'r') as f: # read the contents of the file contents = f.read()
2. Split the contents of the file into individual items using the appropriate delimiter. For example, if the items are separated by commas, you can use the split() method with the comma as the delimiter.
items = contents.split(',')
3. Clean the items by removing any extra white space or special characters. You can use the strip() method to remove white space from the beginning and end of each item.
clean_items = [item.strip() for item in items]
4. Write the cleaned items to a separate file as a Python list. You can use the open() function again to create a new file, and specify the file mode as 'w' (write). Then, use the write() method to write the items to the file as a Python list.
with open('output.py', 'w') as f: f.write('my_list = {}\n'.format(clean_items))
The above code will create a new file called output.py with a Python list variable my_list containing the cleaned items from the original file.
Note that the above method assumes that the items in the original file are all strings. If the items are of a different data type, such as integers or floats, you may need to convert them using the appropriate conversion function, such as int() or float().