Skip to content

Instantly share code, notes, and snippets.

@mwy912
Created October 15, 2020 13:36
Show Gist options
  • Save mwy912/dd5b543358a4c2978b0e7688153692e6 to your computer and use it in GitHub Desktop.
Save mwy912/dd5b543358a4c2978b0e7688153692e6 to your computer and use it in GitHub Desktop.
Created on Skills Network Labs
Display the source blob
Display the rendered blob
Raw
{"cells":[{"cell_type":"markdown","metadata":{},"source":["<center>\n"," <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\">\n","</center>\n","\n","# Write and Save Files in Python\n","\n","Estimated time needed: **15** minutes\n","\n","## Objectives\n","\n","After completing this lab you will be able to:\n","\n","- Write to files using Python libraries\n"]},{"cell_type":"markdown","metadata":{},"source":["<h2>Table of Contents</h2>\n","<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n"," <ul>\n"," <li><a href=\"write\">Writing Files</a></li>\n"," <li><a href=\"copy\">Copy a File</a></li>\n"," </ul>\n","\n","</div>\n","\n","<hr>\n"]},{"cell_type":"markdown","metadata":{},"source":["<h2 id=\"write\">Writing Files</h2>\n"]},{"cell_type":"markdown","metadata":{},"source":[" We can open a file object using the method <code>write()</code> to save the text file to a list. To write the mode, argument must be set to write <b>w</b>. Let’s write a file <b>Example2.txt</b> with the line: <b>“This is line A”</b>\n"]},{"cell_type":"code","execution_count":null,"metadata":{"collapsed":true},"outputs":[],"source":["# Write line to file\n","\n","with open('/resources/data/Example2.txt', 'w') as writefile:\n"," writefile.write(\"This is line A\")"]},{"cell_type":"markdown","metadata":{},"source":[" We can read the file to see if it worked:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Read file\n","\n","with open('/resources/data/Example2.txt', 'r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":["We can write multiple lines:\n"]},{"cell_type":"code","execution_count":null,"metadata":{"collapsed":true},"outputs":[],"source":["# Write lines to file\n","\n","with open('/resources/data/Example2.txt', 'w') as writefile:\n"," writefile.write(\"This is line A\\n\")\n"," writefile.write(\"This is line B\\n\")"]},{"cell_type":"markdown","metadata":{},"source":["The method <code>.write()</code> works similar to the method <code>.readline()</code>, except instead of reading a new line it writes a new line. The process is illustrated in the figure , the different colour coding of the grid represents a new line added to the file after each method call.\n"]},{"cell_type":"markdown","metadata":{},"source":["<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%204/Images/WriteLine.png\" width=\"500\" />\n"]},{"cell_type":"markdown","metadata":{},"source":["You can check the file to see if your results are correct \n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Check whether write to file\n","\n","with open('/resources/data/Example2.txt', 'r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":[" By setting the mode argument to append **a** you can append a new line as follows:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write a new line to text file\n","\n","with open('/resources/data/Example2.txt', 'a') as testwritefile:\n"," testwritefile.write(\"This is line C\\n\")"]},{"cell_type":"markdown","metadata":{},"source":[" You can verify the file has changed by running the following cell:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Verify if the new line is in the text file\n","\n","with open('/resources/data/Example2.txt', 'r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":[" We write a list to a <b>.txt</b> file as follows:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Sample list of text\n","\n","Lines = [\"This is line A\\n\", \"This is line B\\n\", \"This is line C\\n\"]\n","Lines"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write the strings in the list to text file\n","\n","with open('Example2.txt', 'w') as writefile:\n"," for line in Lines:\n"," print(line)\n"," writefile.write(line)"]},{"cell_type":"markdown","metadata":{},"source":[" We can verify the file is written by reading it and printing out the values: \n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Verify if writing to file is successfully executed\n","\n","with open('Example2.txt', 'r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":["We can again append to the file by changing the second parameter to <b>a</b>. This adds the code:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Append the line to the file\n","\n","with open('Example2.txt', 'a') as testwritefile:\n"," testwritefile.write(\"This is line D\\n\")"]},{"cell_type":"markdown","metadata":{},"source":["We can see the results of appending the file: \n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Verify if the appending is successfully executed\n","\n","with open('Example2.txt', 'r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":["<hr>\n"]},{"cell_type":"markdown","metadata":{},"source":["<h2 id=\"copy\">Copy a File</h2> \n"]},{"cell_type":"markdown","metadata":{},"source":["Let's copy the file <b>Example2.txt</b> to the file <b>Example3.txt</b>:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Copy file to another\n","\n","with open('Example2.txt','r') as readfile:\n"," with open('Example3.txt','w') as writefile:\n"," for line in readfile:\n"," writefile.write(line)"]},{"cell_type":"markdown","metadata":{},"source":["We can read the file to see if everything works:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Verify if the copy is successfully executed\n","\n","with open('Example3.txt','r') as testwritefile:\n"," print(testwritefile.read())"]},{"cell_type":"markdown","metadata":{},"source":[" After reading files, we can also write data into files and save them in different file formats like **.txt, .csv, .xls (for excel files) etc**. Let's take a look at some examples.\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Writing a file and saving in .txt format\n","file1 = open(\"myfile.txt\",\"w\")\n","L = [\"This is Delhi \\n\",\"This is Paris \\n\",\"This is London \\n\"]\n","file1.writelines(L)\n","file1.close()"]},{"cell_type":"markdown","metadata":{},"source":["Now go to the directory to ensure the <b>.txt</b> file exists and contains the summary data that we wrote.\n"]},{"cell_type":"markdown","metadata":{},"source":["<hr>\n","<h2>The last exercise!</h2>\n","<p>Congratulations, you have completed your first lesson and hands-on lab in Python. However, there is one more thing you need to do. The Data Science community encourages sharing work. The best way to share and showcase your work is to share it on GitHub. By sharing your notebook on GitHub you are not only building your reputation with fellow data scientists, but you can also show it off when applying for a job. Even though this was your first piece of work, it is never too early to start building good habits. So, please read and follow <a href=\"https://cognitiveclass.ai/blog/data-scientists-stand-out-by-sharing-your-notebooks/\" target=\"_blank\">this article</a> to learn how to share your work.\n","<hr>\n"]},{"cell_type":"markdown","metadata":{},"source":["## Author\n","\n","<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\" target=\"_blank\">Joseph Santarcangelo</a>\n","\n","### Other Contributors\n","\n","<a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>\n","\n","## Change Log\n","\n","| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n","| ----------------- | ------- | ------------- | ------------------------------------ |\n","| 2020-09-09 | 2.1 | Malika Singla | Added the example for writing a file |\n","| 2020-08-28 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n","\n","<hr>\n","\n","## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.3"}},"nbformat":4,"nbformat_minor":2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment