Changes

Jump to: navigation, search

OPS435 Python Lab 5

6 bytes removed, 08:48, 5 September 2017
PART 2 - Writing To Files
::#To demonstrate adding multiple lines, issue the following command:<source lang="python">
f.write('Line 1\nLine 2 is a little longer\nLine 3 is too\n')
</source><br>Once the '''write()''' operation has been run, the final step would be to '''close()''' the file. The file MUST be closed properly or else data will not consistently be written to the file. '''NOTE: Not closing a file can lead to corruption or not changes being made.'''<br><br>
::#Issue the following command to close our file:<source lang="python">
f.close()
::#Issue the following command to view the contents of the file to make sure the write data was saved. <source lang="python">
cat file1.txt # or %cat file2.txt to display the same results as the cat command
</source><br>You will now create a new file called file2.txt, but run multiple write() methods in a series of operations. The ability to write() multiple lines like this allows for writes to take place inside '''loops''' and more complex programs to continuously write to a file.<br><br>
::#Issue the following commands:<source lang="python">
f = open('file2.txt', 'w')
f.write('Last line in file\n')
f.close()
cat file1.txt
</source><br>The final point to make when writing to files is to make 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">
13,420
edits

Navigation menu