Changes

Jump to: navigation, search

OPS435 Python Lab 5

2 bytes removed, 09:47, 5 September 2017
PART 2 - Writing To Files
::#To start, open the ipython3 shell:<source lang="python">
ipython3
</source><br>When opening a file for writing, the ''''w'''' option is specified with the '''open()''' function. When the 'w' option is specified, previous contents inside the file are deleted. This deletion takes place the moment the open() function is executed as opposed to the actual writing process. If the file that is being written to doesn't exist, the file will be created upon the file opening process.<br><br>
::#Let's open a non-existent file (called file1.txt) for writing. Issue the following command:<source lang="python">
f = open('file1.txt', 'w')
::#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')
cp file2.txt.bk file2.txt
cat file2.txt
</source><br>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('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