Skip to content

Instantly share code, notes, and snippets.

@EunkyungGu
Created October 16, 2020 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EunkyungGu/88fe2aad6f394a58c486942ca6f72aa4 to your computer and use it in GitHub Desktop.
Save EunkyungGu/88fe2aad6f394a58c486942ca6f72aa4 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": 1,
"metadata": {},
"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": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n"
]
}
],
"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": 4,
"metadata": {},
"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": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"This is line B\n",
"\n"
]
}
],
"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": 8,
"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": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"This is line B\n",
"This is line C\n",
"\n"
]
}
],
"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": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['This is line A\\n', 'This is line B\\n', 'This is line C\\n']"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"\n",
"This is line B\n",
"\n",
"This is line C\n",
"\n"
]
}
],
"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": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"This is line B\n",
"This is line C\n",
"\n"
]
}
],
"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": 13,
"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": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"This is line B\n",
"This is line C\n",
"This is line D\n",
"\n"
]
}
],
"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": 15,
"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": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line A\n",
"This is line B\n",
"This is line C\n",
"This is line D\n",
"\n"
]
}
],
"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": 17,
"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": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is Delhi \n",
"\n",
"This is Paris \n",
"\n",
"This is London \n",
"\n"
]
}
],
"source": [
"with open(\"myfile.txt\",\"r\") as location:\n",
" for line in location:\n",
" print(line)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"***\n",
"## Self-study\n",
"*by Eunkyung*"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is line 0\n",
"\n",
"This is line 1\n",
"\n",
"This is line 2\n",
"\n",
"This is line 3\n",
"\n",
"This is line 4\n",
"\n",
"This is line 5\n",
"\n"
]
}
],
"source": [
"with open(\"/resources/data/self_study1.txt\",\"w\") as writingself1:\n",
" for i in range(0,6):\n",
" writingself1.write(\"This is line %d\\n\"%i)\n",
" \n",
"with open(\"/resources/data/self_study1.txt\",\"r\") as readingself1:\n",
" for line in readingself1:\n",
" print(line)\n",
" \n",
"with open(\"/resources/data/self_study2.txt\",\"w\") as writingself2:\n",
" with open(\"/resources/data/self_study1.txt\",\"r\") as readingself1:\n",
" for line in readingself1:\n",
" writingself2.write(line)\n",
" \n",
"with open(\"/resources/data/self_study2.txt\",\"a\") as appendingself2:\n",
" appendingself2.write(\"This line was appended\")"
]
},
{
"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",
"language": "python",
"name": "conda-env-python-py"
},
"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.6.11"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment