Skip to content

Instantly share code, notes, and snippets.

@Sparker0i
Created June 28, 2019 11:07
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 Sparker0i/03eaadfafc6400b6b5d64b75fdbb199d to your computer and use it in GitHub Desktop.
Save Sparker0i/03eaadfafc6400b6b5d64b75fdbb199d to your computer and use it in GitHub Desktop.
Created on Cognitive Class Labs
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1>Write and Save Files in Python</h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<p><strong>Welcome!</strong> This notebook will teach you about write the text to file in the Python Programming Language. By the end of this lab, you'll know how to write to file and copy the file.</p>"
]
},
{
"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",
" <p>\n",
" Estimated time needed: <strong>15 min</strong>\n",
" </p>\n",
"</div>\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"write\">Writing Files</h2>"
]
},
{
"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>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"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:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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."
]
},
{
"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\" />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can check the file to see if your results are correct "
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['This is line A\\n', 'This is line B\\n', 'This is line C\\n']"
]
},
"execution_count": 7,
"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": 8,
"metadata": {
"collapsed": false
},
"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: "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"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: "
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"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>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h2 id=\"copy\">Copy a File</h2> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's copy the file <b>Example2.txt</b> to the file <b>Example3.txt</b>:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"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."
]
},
{
"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."
]
}
],
"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.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment