Changes

Jump to: navigation, search

OPS435 Python Lab 5

62 bytes added, 08:28, 5 September 2017
PART 2 - Writing To Files
cp file2.txt.bk file2.txt
cat file2.txt
</source></li><libr>In the event that the data in the file is important and should not be overwritten, we can '''append''' data to the end of the file instead. Use the option 'a' instead of 'w' to perform appending.<br><br></li><li>To demonstrate, issue the following commands:<source lang="python">
f = open('file1.txt', 'a')
f.write('This is the 4th line\n')
f.write('Last line in file\n')
f.close()
</source></li><libr>The final point to make when writing to files is to make sure certain that the values being written are '''strings'''. This means that before trying to place integers, floats, lists, or dictionaries into a file, first either convert the value using '''str() ''' function or extract the specific strings from items in the list. <br><br></li><li>To see how to convert numbers into strings to be stored into a file, issue the following commands:<source lang="python">
my_number = 1000
my_list = [1,2,3,4,5]
f = open('file3.txt', 'w')
f.write(str(my_number) + '\n')
for num in my_list:my_lis
f.write(str(num) + '\n')
f.close()
</source></li>
<li>View Issue the contents of the file3.txt following command to make sure confirm that the '''write data ()''' operation was savedsuccessful.<source lang="python">cat file3.txt # or %cat file3.txt 1000 1 2 3 4 5
</source></li>
</ol>
13,420
edits

Navigation menu