Changes

Jump to: navigation, search

OPS435 Python Lab 5

17 bytes added, 08:10, 5 September 2017
PART 2 - Writing To Files
::#To confirm that the new file exists and is empty, issue the following command:<source lang="python">
ls -l file1.txt
</source>The '''ls -l''' command should work, but if you experience any problems, place a % sign in front of the command. This represents the '''alias''' for the ''ls -l'' command (i.e. '''%ls -l''').<br><br>To add lines of text to the file, you would use the '''write()''' method for the '''file object'''. For safe file management, always end every line with the special character ''''\n'''' to represent a "new line". Multiple lines may also be placed inside a single write operation: simply put the special character ''''\n'''' wherever a line should end.<br><br>
::#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')
f.close()
</source>
::#Issue the following command to view the contents of the file to make sure the write data was saved. The cat command should work, but if you experience any problems, place a % sign in front of the command. This represents the '''alias''' for the cat command (i.e. '''%cat''').<source lang="python">cat file1.txt # or %cat file1file2.txt # should 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">
::#View the contents of the file2.txt to make sure the write data was saved.<source lang="python">
cat file2.txt
</source><br><blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Make Backup Copies of Your Data Files|Since you might make a mistake, and accidentally destroy file contents when writing to your file, it is highly recommended to make backup copies of your files prior to running your Python scripts. This can be particularly useful when performing any future assignment involving writing to files.}}</blockquote><br>
::#Issue the following command to backup both of your newly-created files and confirm backup:<source lang="python">
cp file1.txt file1.txt.bk
13,420
edits

Navigation menu