All Courses

What is the method to convert a list of items from an unformatted text file to a Python list in a separate file?

By Manerushi149@gmail.com, a month ago
  • Bookmark
0

How can I convert an unformatted text file list into a Python list in another file?  

Convert a list of items
Unformatted text file
Python list
Separate file
1 Answer
0
Goutamp777

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().

Your Answer

Webinars

How To Land a Job in Data Science?

Apr 6th (7:00 PM) 190 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More