Writing to a text file - 2 - Answers
Q1. Get the following code working:
value = ['The answer','Chairs','tables']
print(type(value))
newValue = str(value)
print(type(newValue))
Q2. This code creates a list with three elements in it. It then prints out the data type of variable used to store the list. The list is then converted to a string and the data type of the variable used to hold the string is printed out.
Q3. Get this code working:
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. This code creates a list with three elements in it. It then prints out the data type of variable used to store the list. The list is then converted to a string and the data type of the variable used to hold the string is printed out. The program then saves the file in a file called list.txt. It then reads back the contents of the file and prints it, along with the datatype of the variable used to hold what was read back.
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.
value = [10,30,3.14,100]
print(type(value))
newValue = str(value)
print(type(newValue))
with open('list.txt','w',encoding='utf-8') as myFile:
myFile.write(newValue)
with open('list.txt','r',encoding='utf-8') as myFile:
readBack = (myFile.read())
print(readBack)
print(type(readBack))
Q6 - Q7
value = ['The answer','Chairs','tables']
print(type(value))
newValue = ' '.join(value)
print(type(newValue))
with open('list.txt','w',encoding='utf-8') as myFile:
myFile.write(newValue)
with open('list.txt','r',encoding='utf-8') as myFile:
readBack = (myFile.read())
print(type(readBack))
print(readBack)
originalList = readBack.split()
print(type(originalList))
print(originalList)
When the string is converted into a list again, 'The answer' is saved as two elements in the list. It should have been saved as one element.
Q8. If you change your list in your program that uses the split and join methods so the list has some numbers in it e.g.
value = ['The answer',17,'Chairs','tables', 3.14]
Python will generate an error. Split and join only works with strings.
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.