Working with Lists and Files in Python:-

Some tasks may require you to save the contents of a list to a file so the data can be used at a later time. Likewise, some situations may require you to read the data from a file into a list. For example, suppose you have a file that contains a set of values that appear in random order and you want to sort the values. One technique for sorting the values in the file would be to read them into a list, call the list's sort method, and then write the values in the list back to the file.

Saving the contents of a list to a file is a straightforward procedure. In fact, Python file objects have a method named writelines that writes an entire list to a file. A drawback to the writelines method, however, is that it does not automatically write a newline (\n) at the end of each item. Consequently, each item is written to one long line in the file.

File objects in Python have a method named readlines that returns a file's contents as a list of strings. Each line in the file will be an item in the list. The items in the list will include their terminating newline character, which in many cases you will want to strip. Another thing is that when you read numbers from a file into a list, the numbers will have to be converted from strings to a numeric type.