<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python | TekCookie</title>
	<atom:link href="https://tekcookie.com/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://tekcookie.com</link>
	<description>Everything about IT</description>
	<lastBuildDate>Wed, 23 Jun 2021 05:49:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/tekcookie.com/wp-content/uploads/2021/06/cropped-TekCookie-211.png?fit=32%2C17&#038;ssl=1</url>
	<title>Python | TekCookie</title>
	<link>https://tekcookie.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">174510684</site>	<item>
		<title>Web Scraping with Python</title>
		<link>https://tekcookie.com/web-scraping-with-python/</link>
					<comments>https://tekcookie.com/web-scraping-with-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Tue, 04 Aug 2020 06:37:27 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=1344</guid>

					<description><![CDATA[Web Scraping is the method used for extracting or harvesting data from websites. The extracted data is then processed and stored as a more structed form. Everyone of us might have copied some information from websites for our requirements. Web scraping also extracts information from the websites, but in huge volume by means of any [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Web Scraping is the method used for extracting or harvesting data from websites. The extracted data is then processed and stored as a more structed form.</p>



<p>Everyone of us might have copied some information from websites for our requirements. Web scraping also extracts information from the websites, but in huge volume by means of any script of special software&#8217;s. </p>



<p>When we do a web search, search engines present to us tonnes of information from millions of websites. How do they do that? It is done by crawling through the websites and fetching the information to build their database.</p>



<p>This article is about how to scrape information from a demo web page (a simple one) using python.</p>



<p>About legality, please do your research !!!</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Note: This is article only for the purpose of knowledge sharing.</p></blockquote>



<h3 class="wp-block-heading">The demo web page</h3>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/08/SampleSite-1.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1425"/></figure>



<h3 class="wp-block-heading">HTML code of website</h3>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;!DOCTYPE html&gt;
&lt;html lang="en-US"&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Name&lt;/th&gt;
		&lt;th&gt;SerialNo&lt;/th&gt;
		&lt;th&gt;Price&lt;/th&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;Butter&lt;/td&gt;
		&lt;td&gt;22315&lt;/td&gt;
		&lt;td&gt;12&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;Gum&lt;/td&gt;
		&lt;td&gt;11452&lt;/td&gt;
		&lt;td&gt;5&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;Milk&lt;/td&gt;
		&lt;td&gt;55462&lt;/td&gt;
		&lt;td&gt;23&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;Sugar&lt;/td&gt;
		&lt;td&gt;55411&lt;/td&gt;
		&lt;td&gt;18&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>



<h3 class="wp-block-heading">Python code to scrape the information from website</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import requests
import bs4
import csv


#class definition
#This class objects hold the data of each item
class Data_Class:
  col_data_1 = None
  col_data_2 = None
  col_data_3 = None

  def __init__(self, col_data_1, col_data_2, col_data_3):
    self.col_data_1 = col_data_1
    self.col_data_2 = col_data_2
    self.col_data_3 = col_data_3

  def __iter__(self):
    return iter([self.col_data_1, self.col_data_2, self.col_data_3])


#Functions
#This function writes the list of objects to a csv file
def write_csv(data_list, file_path):
  with open(file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data_list)


#This function will fetch the website data and pass the deta to write_csv function
def fetch_webdata(filepath, weburl):
  data_list = list()
  row_count = 0
  #get the website data and parse using beautifulsoup
  response = requests.get(weburl)
  soup = bs4.BeautifulSoup(response.content, 'html.parser')
  #find all the table rows and loop through the items
  allrows = soup.find_all('tr')
  for row in allrows:
    #Fetching the heading
    if (row_count == 0):
      row_count += 1
      allheadings = row.find_all('th')
      head_count = 0
      head_name_1 = ""
      head_name_2 = ""
      head_name_3 = ""
      for heading in allheadings:
        if (head_count == 0):
          head_name_1 = heading.get_text()
        elif (head_count == 1):
          head_name_2 = heading.get_text()
        else:
          head_name_3 = heading.get_text()
        head_count = head_count + 1
      data_class_obj = Data_Class(head_name_1, head_name_2, head_name_3)
      data_list.append(data_class_obj)
      continue
    #Fetching the rows
    #in each row, get the columm and loop through values
    allcols = row.find_all('td')
    col_count = 0
    col_data_1 = ""
    col_data_2 = 0
    col_data_3 = 0
    #loop through the values in the sequence as they appear in the html table
    for col in allcols:
      if (col_count == 0):
        col_data_1 = col.get_text()
      elif (col_count == 1):
        col_data_2 = col.get_text()
      else:
        col_data_3 = col.get_text()
      col_count = col_count + 1
    #assign the vales to object of the declared class "Data_Class"
    data_class_obj = Data_Class(col_data_1, col_data_2, col_data_3)
    #append the object to the list
    data_list.append(data_class_obj)
  #calling the write csv function to write the data to a csv file
  write_csv(data_list, filepath) 


filepath = r'C:\Users\weapon-x\Python\File.csv'
weburl = 'https://tekcookie.com/samplepage.html'
fetch_webdata(filepath, weburl)</code></pre>



<p>The above code will save the data as a csv file</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" width="263" height="127" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/08/sampleSite-outpu-csvt.jpg?resize=263%2C127&#038;ssl=1" alt="" class="wp-image-2792"/></figure>



<p>When the website has multiple tables and complex contents, the code has to be modified to access the required table by the class id, table names, etc.</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Hope this article is informative and thank you for reading.</p></blockquote>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/web-scraping-with-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1344</post-id>	</item>
		<item>
		<title>Reverse a String in Python</title>
		<link>https://tekcookie.com/reverse-a-string-in-python/</link>
					<comments>https://tekcookie.com/reverse-a-string-in-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Sat, 25 Jul 2020 09:46:21 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Reverse a String in Python]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=1382</guid>

					<description><![CDATA[In Python, string object is considered as a sequence of characters represented by double quotes (“”) or single quotes (”). To see how to reverse the string in PowerShell, have a look at https://tekcookie.com/reverse-a-string-in-powershell/ Accessing characters through array index Result: Display full string Result: Reversing the String Reverse string by iterating through array Result Reverse [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In Python, string object is considered as a sequence of characters represented by double quotes (“”) or single quotes (”).</p>



<p>To see how to reverse the string in PowerShell, have a look at <a href="https://tekcookie.com/reverse-a-string-in-powershell/" target="_blank" aria-label="undefined (opens in a new tab)" rel="noreferrer noopener sponsored nofollow">https://tekcookie.com/reverse-a-string-in-powershell/</a></p>



<p><strong>Accessing characters through array index</strong></p>



<pre class="wp-block-code"><code lang="python" class="language-python">s = "tekcookie.com"

#To get the first character
print("First Character: ", s[0])

#To get the last character
print("Last Character: ", s[-1])</code></pre>



<p>Result:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/07/1.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1386"/></figure>



<p><strong>Display full string</strong></p>



<pre class="wp-block-code"><code lang="python" class="language-python">s = "tekcookie.com"

#To display full string
print("String is: ", s)

#Iterating through all indexes
print("String is: ", s[0:len(s):1])

#In short form
print("String is: ", s[::1])

#Skipping alternate characters
print("Skipping alternate characters in String: ", s[::2])</code></pre>



<p>Result:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/07/2.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1387"/></figure>



<hr class="wp-block-separator"/>



<p><strong>Reversing the String</strong></p>



<p>Reverse string by iterating through array</p>



<pre class="wp-block-code"><code lang="python" class="language-python">s = "tekcookie.com"

#Iterating all indexes - 
print("Reversed string:", s[-1:-len(s)-1:-1])

#In Short
print("Reversed string:", s[::-1])</code></pre>



<p>Result</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/07/3.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1389"/></figure>



<p>Reverse string using for loop</p>



<pre class="wp-block-code"><code lang="python" class="language-python">s = "tekcookie.com"

strn = ""
for i in s:
  strn = i + strn
print("Reversed String:", strn)</code></pre>



<p>Result:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/07/4.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1390"/></figure>



<p>Reverse string using reversed method</p>



<pre class="wp-block-code"><code lang="python" class="language-python">s = "tekcookie.com"
print("Reversed string:", ''.join(reversed(s)))</code></pre>



<p>Result:</p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/07/5.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1391"/></figure>



<hr class="wp-block-separator"/>



<p>If you know of other ways to reverse the string in Python, comment below with the code !!!</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading the article.</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/reverse-a-string-in-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1382</post-id>	</item>
		<item>
		<title>Edit Multiple CSV Files using Python</title>
		<link>https://tekcookie.com/edit-csv-files-using-python/</link>
					<comments>https://tekcookie.com/edit-csv-files-using-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Thu, 30 Apr 2020 19:30:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Edit multiple CSV files using Python]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=1126</guid>

					<description><![CDATA[In my previous post, we have seen how to read CSV files https://tekcookie.com/read-csv-file-using-python/ and how to write data to text files https://tekcookie.com/write-to-a-text-file-using-python/ This article is about how to modify or edit multiple CSV files using Python. Suppose we have the daily sale data of apples as shown below. Our task is to add one column [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In my previous post, we have seen how to read CSV files <a href="https://tekcookie.com/read-csv-file-using-python/">https://tekcookie.com/read-csv-file-using-python/</a> and how to write data to text files <a href="https://tekcookie.com/write-to-a-text-file-using-python/">https://tekcookie.com/write-to-a-text-file-using-python/</a></p>



<p>This article is about how to modify or edit multiple CSV files using Python.</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/icons8-csv-64.png?resize=139%2C139&#038;ssl=1" alt="" width="139" height="139"/></figure></div>



<p>Suppose we have the daily sale data of apples as shown below. Our task is to add one column to the right and calculate the total sale in each week.</p>



<p><strong>Source Data</strong></p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/Source.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1129"/></figure>



<p><strong>Required Result</strong></p>



<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/result.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1130"/></figure>



<p><strong><em>Source content in raw csv</em></strong></p>



<pre class="wp-block-preformatted">Weeks,Monday,Tuesday,Wednesday,Thursday,Friday
Week-1,20,41,22,65,42
Week-2,23,23,56,44,85
Week-3,54,54,68,56,44
Week-4,12,89,32,23,65</pre>



<p><strong>Logic</strong></p>



<ul class="wp-block-list"><li>Open the CSV file and read the data</li><li>Iterate through each row and calculate the sum of values for each week.</li><li>Append the calculated data to the row</li><li>Overwrite to the existing file</li></ul>



<h2 class="wp-block-heading">Python code to edit CSV file</h2>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import csv


# function to write the list to csv file
def write_csv(data_list, file_path):
    with open(file_path, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data_list)


# function to read CSV to list
def read_csv(file_path):
    csv_data_list = []
    source_file = open(file_path)
    csv_data = csv.reader(source_file)
    for data in csv_data:
        # converting the data to list
        csv_data_list += [data]
    source_file.close()
    return csv_data_list


# main function
def edit_csv_main(file_path):
    csv_data = read_csv(file_path)
    final_list = []
    for row_num in range(0, len(csv_data)):
        # assigning the list to a variable for readability
        data = csv_data[row_num]
        total = 0
        # adding heading to the first row
        if row_num == 0:
            data.append("Total")
        else:
            # total of each item in the row except the first item as it is a text
            for numbers in data[1:len(data)]:
                total += int(numbers)
            # append the result to end of the list
            data.append(total)
        # append the result to final list
        final_list += [data]

    # calling csv write function
    write_csv(final_list, file_path)

# calling the main function with path to the source file
edit_csv_main(r'D:\BLOG\Python\WriteCSV\File-17-04-2020.csv')
</code></pre>



<p>Running the above code will give us the required result.</p>



<p>If there are multiple files in which the data has to be modified, a small change to the above code can address it.</p>



<h2 class="wp-block-heading">Python code to edit multiple CSV file</h2>



<p>Suppose all the CSV files are kept at &#8220;D:\BLOG\Python\WriteCSV\&#8221; and the file names are File-&lt;date&gt;.csv</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/csvFiles.jpg?resize=227%2C162&#038;ssl=1" alt="" class="wp-image-1131" width="227" height="162"/></figure>



<p>The way is to get path of the file of type CSV having names starting with <em>File*</em> and pass it to the code (Line# 53 in the code below).</p>



<p>We use glob function to find the file names in the folder (Line# 27 in the code below).</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import csv
import glob


# function to write the list to csv file
def write_csv(data_list, file_path):
    with open(file_path, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data_list)
        #for data in data_list:
        #    writer.writerow(data)

# function to read CSV to list
def read_csv(file_path):
    csv_data_list = []
    source_file = open(file_path)
    csv_data = csv.reader(source_file)
    for data in csv_data:
        # converting the data to list
        csv_data_list += [data]
    source_file.close()
    return csv_data_list


# main function
def edit_csv_main(file_path):
    file_names = glob.glob(file_path)
    for file_path in file_names:
        csv_data = read_csv(file_path)
        final_list = []
        for row_num in range(0, len(csv_data)):
            # assigning the list to a variable for readability
            data = csv_data[row_num]
            total = 0
            # adding heading to the first row
            if row_num == 0:
                data.append("Total")
            else:
                # total of each item in the row except the first item as it is a text
                for numbers in data[1:len(data)]:
                    total += int(numbers)
                # append the result to end of the list
                data.append(total)
            # append the result to final list
            final_list += [data]

        # calling csv write function
        write_csv(final_list, file_path)


# calling the main function
# here the 
edit_csv_main(r'D:\BLOG\Python\WriteCSV\File*.csv')</code></pre>



<p>Running the above code will edit all the CSV files in the mentioned location having their names starting with File*</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading my post. Hope this is informative for you.</p></blockquote>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/edit-csv-files-using-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1126</post-id>	</item>
		<item>
		<title>Write to a text file using Python</title>
		<link>https://tekcookie.com/write-to-a-text-file-using-python/</link>
					<comments>https://tekcookie.com/write-to-a-text-file-using-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Sun, 19 Apr 2020 16:58:33 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[create text file using python]]></category>
		<category><![CDATA[write text file using python]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=1023</guid>

					<description><![CDATA[This article will describe how to write content to a text file using python Write one line to text file Set the argument to &#8216;w&#8217; to write to a file. If the file does not exists, new file is created Output: Write two lines to text file Output: Append data to a text file Set [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This article will describe how to write content to a text file using python</p>



<h2 class="wp-block-heading">Write one line to text file</h2>



<p>Set the argument to &#8216;w&#8217; to write to a file. If the file does not exists, new file is created</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">file = open("demo.txt", 'w')
file.write("this is first line")
file.close()</code></pre>



<p>Output:</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/1Line.jpg?resize=364%2C176&#038;ssl=1" alt="" class="wp-image-1024" width="364" height="176"/></figure>



<h2 class="wp-block-heading">Write two lines to text file</h2>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">file = open("demo.txt", 'w')
file.write("this is first line")
file.write("\n")
file.write("this is second line")
file.close()</code></pre>



<p>Output:</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/2Lines.jpg?resize=361%2C177&#038;ssl=1" alt="" class="wp-image-1025" width="361" height="177"/></figure>



<h2 class="wp-block-heading">Append data to a text file</h2>



<p>Set the argument to &#8216;a&#8217; to append to a file. If the file does not exists, new file is created</p>



<pre class="wp-block-preformatted">"r" - Default mode, open the file in read mode
"x"&nbsp;- Create a file, returns an error if the file exist
"a" - Append to the file, will create a file if the specified file does not exist
"w"&nbsp;- Write to the file, will create a file if the specified file does not exist</pre>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">file = open("demo.txt", 'a')
file.write("\n")
file.write("this is third line")
file.write("\n")
file.write("this is fourth line")
file.close()</code></pre>



<p>Output:</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/append.jpg?resize=372%2C182&#038;ssl=1" alt="" class="wp-image-1027" width="372" height="182"/></figure>



<h2 class="wp-block-heading">Write a list of string to text file</h2>



<pre class="wp-block-code"><code class="">string = ["first line", "\n", "second line", "\n", "third line"]
file = open("demo.txt", 'w')
file.writelines(string)
file.close()</code></pre>



<p>Note: file.write() function will write string to text file and file.writelines() will write a list of strings to text file</p>



<p>Output:</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/listtotext.jpg?resize=371%2C178&#038;ssl=1" alt="" class="wp-image-1028" width="371" height="178"/></figure>



<h2 class="wp-block-heading">Write from 1 to 10 to text file</h2>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">file = open("demo.txt", 'w')
for num in range(1,10):
    file.write(str(num) + "\n")
file.close()</code></pre>



<p>Output:</p>



<figure class="wp-block-image size-large is-resized"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/range.jpg?resize=365%2C295&#038;ssl=1" alt="" class="wp-image-1030" width="365" height="295"/></figure>



<h2 class="wp-block-heading">Copy content from one file to other</h2>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">file = open("demo.txt")
with open("dest_demo.txt",'w') as dest_demo:
    dest_demo.writelines(file.readlines())
file.close()</code></pre>



<p>Copy content from <strong>demo.txt</strong> to <strong>dest_demo.txt</strong></p>



<p>Output:</p>



<div class="wp-block-columns are-vertically-aligned-center is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/range-2.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1033"/></figure>
</div>



<div class="wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow">
<p class="has-text-align-center" style="font-size:58px"><strong>&gt;</strong></p>
</div>



<div class="wp-block-column is-vertically-aligned-center is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-large"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/dest_demo-1.jpg?w=1080&#038;ssl=1" alt="" class="wp-image-1034"/></figure>
</div>
</div>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading this article. Hope this is helpful to you.</p></blockquote>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/write-to-a-text-file-using-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1023</post-id>	</item>
		<item>
		<title>Read CSV file using Python</title>
		<link>https://tekcookie.com/read-csv-file-using-python/</link>
					<comments>https://tekcookie.com/read-csv-file-using-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Mon, 30 Mar 2020 11:52:32 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Read csv file]]></category>
		<category><![CDATA[read csv using python]]></category>
		<guid isPermaLink="false">https://tekcookie.com/?p=508</guid>

					<description><![CDATA[In this article, we will see how to read information from a CSV file and modify the imported data using Python. CSV package is used to read csv file information. Guys, click me to have a look at my article describing how to backup up network devices using Python. Tip: I&#8217;m using PyCharm community edition [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, we will see how to read information from a CSV file and modify the imported data using Python. CSV package is used to read csv file information.</p>



<p>Guys, <strong><a rel="noreferrer noopener" href="https://tekcookie.com/automate-cisco-switch-backup-using-python/" target="_blank">click me </a></strong>to have a look at my article describing how to backup up network devices using Python.</p>



<p>Tip: I&#8217;m using PyCharm community edition IDE for writing Python scripts.</p>



<p>Following csv file is saved at C:\SW\data.csv</p>



<p>The first row in the csv represent the heading </p>



<pre class="wp-block-preformatted">Name,Price,qty
Mango,20.3,4
Orange,23.1,6
Apple,56.3,9</pre>



<p></p>



<h3 class="wp-block-heading">Read and print CSV file</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

print(list(csvData))
sourceFile.close()</code></pre>



<hr class="wp-block-separator"/>



<pre class="wp-block-preformatted"><strong>Output:</strong>
[['Name', 'Price', 'qty'], ['Mango', '20.3', '4'], ['Orange', '23.1', '6'], ['Apple', '56.3', '9']]</pre>



<h3 class="wp-block-heading">Looping through CSV file</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import csv 

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)
for rows in csvData:
    print(rows)

sourceFile.close()</code></pre>



<hr class="wp-block-separator"/>



<pre class="wp-block-preformatted"><strong>Output:</strong> 
['Name', 'Price', 'qty']
['Mango', '20.3', '4']
['Orange', '23.1', '6']
['Apple', '56.3', '9']</pre>



<h3 class="wp-block-heading">Print data without heading</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)
for rows in csvData:
#first line represent heading
    if csvData.line_num == 1:
        continue
    print(rows)

sourceFile.close()</code></pre>



<hr class="wp-block-separator"/>



<pre class="wp-block-preformatted"><strong>Output:</strong>
['Mango', '20.3', '4']
['Orange', '23.1', '6']
['Apple', '56.3', '9']</pre>



<h3 class="wp-block-heading">Print the items from which the price is greater than 22</h3>



<pre class="wp-block-code"><code lang="powershell" class="language-powershell line-numbers">import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

#for serial number while displaying the data 
r_count = 1

#each row item is assigned to variables name, price and quantity 
for name, price, quantity in csvData:
    if csvData.line_num == 1:
        continue
    if float(price) &gt; 22:
        print("{}. Price of {} is {}".format(r_count, name, price))
        r_count += 1

sourceFile.close()</code></pre>



<hr class="wp-block-separator"/>



<pre class="wp-block-preformatted"><strong>Output:</strong> 
Price of Orange is 23.1
Price of Apple is 56.3 </pre>



<h2 class="wp-block-heading">Adding column to the list of item</h2>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">inport csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

#adding extra column to the list
newlist = [x + [0] for x in csvData]
print(newlist) #Output - 1

#to get the data without heading (skipping the first row)
newlist = newlist[1:len(newlist)]
print(newlist)  #Output - 2

#below code will calculate the total amount to newely added column
# newColumn = Price * Quantity
r_count = 1
newlist1 = []
for row in newlist:
    row[3] = float(row[1]) * float(row[2])
    newlist1.append(row)

print(newlist1)  #Output - 3

sourceFile.close()</code></pre>



<hr class="wp-block-separator"/>



<pre class="wp-block-preformatted"><strong>Output - 1:</strong>  
[['Name', 'Price', 'qty', 0], ['Mango', '20.3', '4', 0], ['Orange', '23.1', '6', 0], ['Apple', '56.3', '9', 0]] 

<strong>Output - 2:</strong>  
[['Mango', '20.3', '4', 0], ['Orange', '23.1', '6', 0], ['Apple', '56.3', '9', 0]]   

<strong>Output - 3:</strong>  
[['Mango', '20.3', '4', 81.2], ['Orange', '23.1', '6', 138.6], ['Apple', '56.3', '9', 506.7]]</pre>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Thank you for reading my post. Hope this is helpful to you.</p></blockquote>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/read-csv-file-using-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">508</post-id>	</item>
		<item>
		<title>Automate Cisco switch backup using Python</title>
		<link>https://tekcookie.com/automate-cisco-switch-backup-using-python/</link>
					<comments>https://tekcookie.com/automate-cisco-switch-backup-using-python/#respond</comments>
		
		<dc:creator><![CDATA[jeffythampi]]></dc:creator>
		<pubDate>Sun, 30 Jun 2019 13:15:54 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Cisco switch backup using Python]]></category>
		<category><![CDATA[Cisco switch backup with Python]]></category>
		<category><![CDATA[switch backup using Python]]></category>
		<category><![CDATA[telnet using python]]></category>
		<guid isPermaLink="false">https://adminscripter.wordpress.com/?p=126</guid>

					<description><![CDATA[This python script reads the device information from a csv file and fetches its configuration via telnet session and save to specified location. CSV Template: deviceIp,userName,password 192.168.1.1,admin,secretpwd 192.168.1.2,admin,secretpwd2 The script initiates telnet session with the device along with userId and password to login into enable mode and executes &#8220;show run&#8221; command to fetch the configuration [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>This python script reads the device information from a csv file and fetches its configuration via telnet session and save to specified location.</p>



<p>CSV Template:</p>



<pre class="wp-block-preformatted"><strong>deviceIp,userName,password</strong> 
192.168.1.1,admin,secretpwd 
192.168.1.2,admin,secretpwd2</pre>



<p>The script initiates telnet session with the device along with userId and password to login into enable mode and executes &#8220;show run&#8221; command to fetch the configuration</p>



<hr class="wp-block-separator"/>



<h3 class="wp-block-heading">Python code to fetch switch configuration:</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import telnetlib as tel
import csv
import datetime
import os


#Declaration
#path of the csv file
#deviceFilePath = "D:/Script/DeviceIp.csv"
#path to save the backup files
#directoryLocation = "D:/Script/"


#Methods
###This method initiate telnet connection to devices
def Initiate_Telnet(indexCount, hostIP, userId, passwd, directoryLocation):
    commands_ShowConfig = "sh run"
    commands_terminalLength = "terminal length 0"
    response = os.system("ping -n 1 -w 700 " + hostIP)
    if response == 0:
        try:
            #connecting to host device
            telConnection = tel.Telnet(hostIP, timeout=2)

            #sending username value and password value
            uName = telConnection.read_until('Username:'.encode('utf-8'), timeout=5)
            telConnection.write(userId.encode('utf-8') + b"\n")
            uPass = telConnection.read_until('Password:'.encode('utf-8'), timeout=5)
            telConnection.write(passwd.encode('utf-8') + b"\n")

            #checking for "#"
            telConnection.write(b"\n")
            mode = telConnection.read_until('#'.encode('utf-8'), timeout=5)
            #x = b' \r\nBZPDAMG0204#'
            mode = str(mode.decode('utf-8'))

            if(mode[-1] == "#"):
                #sending terminal length command to get full configuration
                telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
                telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")
            elif(mode[-1] == ":"):
                outputData = b"Password Wrong"
            elif(mode[-1] == "&gt;"):
                outputData = b"Not Enable Mode"


            #sending terminal length command to get full configuration
            #telConnection.write(commands_terminalLength.encode('utf-8') + b"\n")
            #telConnection.write(commands_ShowConfig.encode('utf-8') + b"\n")

            #read till end, so passing a string which may not appear in the configuration
            outputData = telConnection.read_until('stringNotInConfiguration'.encode('utf-8'), timeout=5)

            #close telnet connection
            telConnection.close()
        except:
            outputData = b"telnet not available"
    else:
        outputData = b"Host not pinging"

    #exporting the data to text file and close file
    Write_Info_toFile(directoryLocation, hostIP, outputData)

    return (indexCount, hostIP)
#end Initiate_Telnet


###This method writes info to file
def Write_Info_toFile(directory, fileName, dataString):
    datestring = datetime.datetime.now()
    datestring = str(datestring).replace(':','_').replace('-','_').replace(' ','__').split('.')[0]
    
    #exporting the data to text file and close file
    dataString = dataString.decode('utf-8')
    
    #validation
    if(dataString == "telnet not available"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == "Host not pinging"):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " " + dataString + "\n"
    elif(dataString == ""):
        text_file = open(directory + "Log_backup_.txt", "a+")
        dataString = fileName + " Login Failed" + "\n"
    else:
        text_file = open(directory + fileName + "_backup_" + datestring + ".txt", "w")

    text_file.write(dataString)
    text_file.close()
#end Write_Info_toFile

#start function
def Start_Telnet(deviceFilePath = "D:/Script/DeviceIp.csv", directoryLocation = "D:/Script/"):
    with open(deviceFilePath) as csvDeviceDetails:
        csdData = csv.reader(csvDeviceDetails, delimiter=',')
        #print(csdData)
        lineCount = 0
        for (ipAddress, userName, password) in csdData:
            if(lineCount == 0):
                #First entry is heading
                lineCount += 1
            else:
                lineCount += 1
                Initiate_Telnet(0, ipAddress, userName, password, directoryLocation)

Start_Telnet("D:/Script/DeviceIp.csv", "D:/Script/")</code></pre>



<p>Note: This works for switches which has login to &#8220;enable mode&#8221;, for other modes, extra conditions has to be added.</p>



<div style="height:70px" aria-hidden="true" class="wp-block-spacer"></div>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Hope you liked this article and thank you for reading</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://tekcookie.com/automate-cisco-switch-backup-using-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">126</post-id>	</item>
	</channel>
</rss>
