Back

Writing to a text file - 2

The read and write methods only work with strings! So what do you do if you want to store numbers or lists, or dictionaries and so on in a file?  You have a number of choices. If the data is relatively simple, you could simply convert the data into a string and then store it. When you read it back, you would need to convert the data back into its original format. A much easier solution is to use the pickle module, which will will discuss in another exercise.

Q1. Get the following code working:

value = ['The answer','Chairs','tables']
print(type(value))
newValue = (str(value))
print(type(newValue))

Q2. Describe what the above code does.
Q3. Modify the code so it now looks like this:

1    value = ['The answer','Chairs','tables']
2    print(type(value))
3    newValue = str(value)
4    print(type(newValue))
5    
6    with open('list.txt','w',encoding='utf-8') as myFile:
7        myFile.write(newValue)
8
9    with open('list.txt','r',encoding='utf-8') as myFile:
10      readBack = (myFile.read())
11      print(readBack)
12      print(type(readBack))

Q4. Describe what this code does.
Q5. Write a list of numbers. Convert the numbers into a string and then save it to a file. Then read back the numbers from the file. Use type to prove what data type you are working with at various points in your program.
Q6. In the program used in Q3, change line 3 so that it converts the list into a string using the join method. If you are not sure how to do this, refer to the Python documentation or other online resources.
Q7. In the program used in Q3, add extra lines so that it converts the string into list using the split method. If you are not sure how to do this, refer to the Python documentation or other online resources. Have you spotted a problem with the elements in the resulting list after running the code successfully?
Q8. Change line 1 in the program that uses the split and join methods, so that the list has some numbers in it e.g. 

value = ['The answer',17,'Chairs','tables', 3.14]

What was the result of running the program?

Reading and writing strings to files can be useful for the right problem but it can also present challenges for the wrong set of circumstances. However, Python has a superb module called pickle, which will allow you to take almost any data structure or set of data and save and unsave it easily. 

Back