Basic Python exercises and basic python

Source: Internet
Author: User

Basic Python exercises and basic python

Recently, you need to learn Python for your work. In order not to be able to extricate themselves from the language details, I made three simple exercises according to the learning plan for the python part of the widely spread "Programmer technical level training guide" on the Internet, I have a preliminary understanding of python.


1. Use open/csv to read and write files.
1 _ author _ = 'xuqiang '2 #-*-coding: UTF-8-*-3 import csv 4 import sys 5 6 # csv operation, file format is not important, the most important thing is that the file content must conform to the format, rather than the file extension # use open to process 9 print ("line by line processing \ n ") 10 for line in open ("Sample.txt"): # obtain a row of 11 title, year, director = line. split (",") 12 print (year, title) 13 14 for line in open ("Sample.txt"): # Take a row 15 title, year, director = line. split (",") 16 print (title, director) 17 18 # Use CSV to process files in CSV format 19 print ("\ ncsv processing") 20 reader = csv. reader (open ("Sample.txt") 21 for title, year, director in reader: 22 print title, director23 24 25 # Use CSV for Row-by-row processing. modified the CSV format file 26 print "\ n change separator" 27 class SKV (csv. excel): 28 delimiter = ";" 29 csv. register_dialect ("SKV", SKV) 30 reader = csv. reader (open ("Sample. ddd ")," SKV ") 31 for title, year, director in reader: 32 print year, title33 34 print (" \ n change separator simple version ") 35 reader = csv. reader (open ("Sample. ddd "), delimiter ="; ") 36 for title, year, director in reader: 37 print year, title38 39 40 41 # Use CSV to write data to a CSV file 42 print ("\ n read the data and store it in a CSV file ") 43 reader = csv. reader (open ("Sample. ddd "), delimiter ="; ") 44 data = [] 45 for title, year, director in reader: 46 tup = (title, year, director) # store the data in the productkey, devicename, and devicesecret. append (tup) # store the tuples to the list 48 49 newfile = open('outCsv.csv ', 'w') # a new file 50 sys. stdout = newfile # sys. stdout was originally in the console. We redirected to newfile 51 writer = csv. writer (sys. stdout) 52 53 for item in data: # list iteration 54 writer. writerow (item) # write data in one row

 

2. traverse the file system and sort the traversal results
1 _ author _ = 'xuqiang '2 #-*-coding: UTF-8-*-3 4 import OS 5 import OS. path 6 import time 7 import operator 8 9 rootdir = "/home/xuqiang/newfiles" 10 11 12 #1. Use OS. walk performs folder traversal and directly outputs the traversal result 13 14 # OS. walk recursively traverses the entire folder. This method returns a triple for each directory. (dirpath, dirnames, filenames) 15 # parent: dirnames is generally one. The current large folder name is 16 # dirnames: all folder names in this folder 17 # filenames: the names of all files in this folder 18 for parent, dirnames, filenames in OS. walk (rootdir): 19 for dirname in dirnames: 20 print "parent is:" + parent21 print "dirname is: "+ dirname + '\ n' 22 23 24 for filename in filenames: 25 print" parent is: "+ parent26 print" filename is: "+ filename27 print" the full name of the file is: "+ OS. path. join (parent, filename) + '\ n' # output file path information 28 29 30 31 32 #2. Use OS. path. walk for folder traversal, write the traversal result into the File 33 34 # change the time in the file attribute to '2017-1-12 00:00:00 format '35 def formattime (localtime ): 36 endtime = time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (localtime) 37 return endtime38 39 # searchdir IS OS. path. the callback function of the walk, OS. path. the walk recursively traverses the folder 40 # dirname: path 41 # names: file list (only file names) 42 def searchdir (arg, dirname, names): 43 for filespath in names: 44 fullpath = OS. path. join (dirname, filespath) # path name + file name = file absolute path 45 statinfo = OS. stat (fullpath) # File Attribute 46 sizefile = statinfo. st_size # file size 47 creattime = formattime (statinfo. st_ctime) # creation time 48 maketime = formattime (statinfo. st_mtime) # modification time 49 readtime = formattime (statinfo. st_atime) # browsing time 50 if OS. path. isdir (fullpath): # determine whether it is a folder or FILE 51 filestat = 'dir' 52 else: 53 filestat = 'file' 54. Write the result to 55 open ('test.txt ', 'A' in test.txt '). write ('[% s] path: % s file size (B): % s creation time: % s modification time: % s browsing time: % s \ r \ n' % (filestat, fullpath, sizefile, creattime, maketime, readtime) 56 57 OS. path. walk (rootdir, searchdir, () 58 59 60 61 62 63 64 #3. Use OS. list Directory Traversal, and sort the traversal results according to different requirements 65 tuplist = [] 66 for I in OS. listdir (rootdir): 67 fullpath = OS. path. join (rootdir, I) 68 statinfo = OS. stat (fullpath) # File Attribute 69 sizefile = statinfo. st_size # file size 70 creattime = formattime (statinfo. st_ctime) # creation time 71 if OS. path. isfile (fullpath): 72 tup = {'filename': I, 'filesize': sizefile, 'filetime': creattime} 73 tuplist. append (tup) 74 75 tuplist. sort (key = operator. itemgetter ('filetime') # sort by creation time 76 print tuplist77 tuplist. sort (key = operator. itemgetter ('filesize') # sort by file size 78 print tuplist79 tuplist. sort (key = operator. itemgetter ('filename') # sort by file name 80 print tuplist

 

3. sqlite database operations, a simple select operation.
1 __author__ = 'xuqiang'2 import  sqlite33 cx = sqlite3.connect("btopp.db")4 cu=cx.cursor()5 cu.execute("select * from btopp")6 print cu.fetchall()

 

 

Reference: http://www.jb51.net/article/65792.htm Python methods for Traversing specified files and folders

Introduction to http://coolshell.cn/articles/4990.html programmer technical skills

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.