【學神-RHEL7】P3-文件操作和列表的使用

本節所講內容:

       1)文件的基本操作

       2)列表的基本操作

       3)元組的介紹

       4)實戰:創建一個購物程序

 

文件的基本操作

3.1          打開文件

python中使用open函數來打開文件(默認函數方式,可以省略)

語法格式:

open(文件名,文件模式,緩衝)

其中,文件模式和緩衝都是可選項

>>> f =open('name_list')

 

如果打開的文件不存在,會出現以下報錯

>>> f = open('name')

Traceback (most recent calllast):

  File"<stdin>", line 1, in <module>

IOError: [Errno 2] No suchfile or directory: 'name'

 

3.1.1       文件模式

open函數中模式參數的常用值

描述

r

讀模式

w

寫模式

a

追加模式

b

二進制模式(可添加到其他模式中使用)

+

讀/寫模式(可添加到其他模式中使用)

 

b’模式改變處理文件的方法。一般來說,Python假定處理的是文本文件(包含字符)。通常這樣做不會有任何問題。但如果處理的是一些其他類型的文件(二進制文件),比如聲音剪輯或者圖像,那麼應該在模式參數中增加‘b’。參數 ‘b’可以用來讀取一個二進制文件。

 

3.1.2       緩衝

open函數的第3個參數(可選)控制着文件的緩衝。如果參數是0(或者False),I/O(輸入/輸出)就是無緩衝的(所有的讀寫操作都直接針對硬盤);如果是1(或者是True),I/O就是有緩衝的(意爲着Python使用內存來代替硬盤,讓程序更快,只有使用flush或者close是纔會更新硬盤上的數據)。大於1的數字代表緩衝區的大小(單位是字節),-1(或者是任何負數)代表使用默認的緩衝區大小。

 

3.2          基本的文件方法

3.2.1       寫文件

>>> newfile =file('a.txt','w')                                 #創建一個新的文件a.txt

>>>newfile.write('Hello,World!!!')                        #在文件中寫入“Hello,World!!!”

>>> newfile.flush()                                               #刷新文件內容

>>> newfile.close()                                               #關閉文件

 

在另外一個終端查看發現已經生成了a.txt文件,查看文件內容已經生成

注:在Python中對文件進行寫入操作時,默認保存在內存中1024字節的內容,在沒有對文件執行close關閉時,不寫入磁盤,這樣有利於提高運行效率,如果寫入的內容操作1024字節,將會自動寫入磁盤

 

補充一下:

python中中文的輸入方式

Python默認的字符編碼ASCII,如果要想讓輸出內容顯示中文在腳本中轉換一下字符編碼

#coding=utf-8

 

[root@xuegod163 test]# ls

a.txt 

[root@xuegod163 test]# cata.txt

Hello,World!!![root@xuegod163test]#

 

注:

1)如果這裏要換行顯示,可以在寫入的內容之後加上換行符“\n”

>>>newfile.write('Hello,World!!!\n')

2)如果原本已經存在a.txt文件,再次進行寫操作的話,將會重新創建文件

>>> newfile =file('a.txt','w')

>>> newfile =file('a.txt','w')

執行完此操作後再次查看a.txt,發現內容爲空

3)在Python中要慎用‘w’

 

3.2.2       讀文件

>>> f =file('a.txt','r')                                                          #指定文件模式爲讀模式  

>>> f.read()                                                                        #讀取文件全部內容

'Hello,Girl!!!Hello,Boy!!!Hello,Boy!!!\nHello,Boy!!!\n'

 

>>> f =file('a.txt','r')

>>> f.read(5)                                                                       #指定讀文件的字節數

'Hello'

>>> f.read()                                                          #再次執行,讀取文件剩下的全部內容

'!!!Hello,Boy!!!Hello,Boy!!!\nHello,Boy!!!\n'

 

>>> f =file('name_list','r')                                    #文件模式“r”可以省略

>>> f.readline()                                                    #逐行讀取文件內容

'01\tZhaoXiangJie\tIT\t99\t99\t99\t99\r\n'           #文件第一行

>>> f.readline()                                     

'02\tLiuBei\t\tSHU\t98\t78\t83\t80\r\n'                #文件第二行

…………

 

3.2.3       追加文件

>>> f =file('a.txt','a')

>>>f.write('Hello,Boy!!!\n')

>>> f.flush()

>>> f.close()

 

[root@xuegod163 test]# cata.txt

Hello,Girl!!!Hello,Boy!!!

 

3.2.4       管式輸出

cat   文件  | python  腳本

cat讀取到的文件的內容通過管道作爲腳本執行的標準輸入(stdin),腳本中通過插入sys模塊,引用文件的內容

 

例:

[root@localhost ~]# vimpipe.py

#!/usr/bin/env python

import sys

text = sys.stdin.read()

words = text.split()

wordcount = len(words)

print "Wordcount:%s" % wordcount

 

[root@localhost ~]# catexample.txt

Nice to meet you

Today is a sunny.

 

執行結果

[root@localhost ~]# catexample.txt  | python pipe.py

Wordcount: 8

 

注:split是字符串處理的一種方法,把字符串轉換成列表的格式

>>> a = 'nice tomeet you'

>>> a.split()

split默認的分隔符是空格, 可以進行自定義

>>> b.split('/')

['', 'usr', 'bin','python']

 

3.2.5       在文件的指定位置進行寫操作

python中通過seek方法可以定位到寫的位置

>>> f =file('a.txt','w')

>>>f.write('0123456789')

>>> f.seek(5)                                                 #定位到第五個字節位

>>>f.write('Hello,World!')

>>> f.flush()

>>> f.close()

>>> f =file('a.txt','r')

>>> f.read()

'01234Hello,World!'

 

tell方法返回當前文件的位置

>>> f =file('a.txt','r')

>>> f.read(3)

'012'

>>> f.read(2)

'34'

>>> f.tell()

5

 

注:Python中函數有很多,不會使用時要學會使用help進行查詢

>>> help(file.tell)

Help on method_descriptor:

 

tell(...)

tell() -> current file position, an integer (may be along integer).

 

3.2.6       文件內容替換

語法格式

for   linein    fileinput.input(“filepath”,inplace=1)

       line = line.replace(“oldtext”,”newtext”)

       print line

 

例:

[root@localhost ~]# viminput.py

#!/usr/bin/env  python

import fileinput

for line infileinput.input('a.txt',backup='bak',inplace=1):

        line = line.replace('world','Python')

        print line

fileinput.close()

 

執行腳本之後查看a.txt

[root@localhost ~]# cata.txt

Hello,Python!

 

而且在當前目錄下生成bak結尾的文件

 

inplace=1:標準輸出會被重定向到打開文件;backup='bak',:替換文件內容之前備份後綴以bak結尾

 

3.2.7       修改文件內容

[root@localhost ~]# vimwith.py

#!/usr/bin/env python

with open('a.txt','r+') as f:

        old = f.read()

        f.seek(13)

        f.write('new line\n' + old)

 

查看文件內容

[root@localhost ~]# cata.txt

Hello,Python!new line

Hello,Python!

 

3.3          列表的基本使用

列表是Python的6種內建序列(還有元組,字符串,Unicode字符串,buffer對象,xrange對象)之一,列表內的值可以進行更改,操作靈活,在Python腳本中應用非常廣泛

列表的語法格式

[ ‘元素1’,‘元素2’,‘元素3’,……,‘元素n’]

 

在需要操作一組數值的時候,序列很好用。可以通過序列表示數據庫中一個人的信息——第一個元素是姓名,第二個元素是年齡。根據上述內容編寫一個列表

>>> zhangsan =['zhangsan',18]

>>> lisi =['lisi',19]

>>>database=[zhangsan,lisi]

>>> database

[['zhangsan', 18],['lisi', 19]]

 

3.3.1       索引

序列中的所有元素都是有編號的,從0開始遞增。這些元素可以通過編號分別訪問

>>> company ='xuegod'

>>> company[0]

'x'

 

所有序列都可以通過這種方式進行索引,使用負數索引時,Python會從右邊,也就是從最後一個元素開始計數。最後一個元素的位置編號是-1(不是-0,避免和第一個元素重合)

>>> company[-1]

'd'

 

字符串可以直接進行索引,不需要通過變量進行引用

>>> 'hello'[1]

'e'

 

可以直接對函數調用的返回結果進行索引

>>> ready =raw_input('Are you ready?(yes or no)')[0]

Are you ready?(yes or no)yes

>>> ready

'y'

 

實戰:編寫一個代碼程序,根據用戶輸入打印出時間日期

 

#!/usr/bin/python

#According to the given date(date) (month) (year) in the form of digital print out

months = [

'January',

'February',

'March',

'April',

'May',

'June',

'July',

'August',

'September',

'October',

'November',

'December',

]

#With 1 ~ 31 number as the endof the list

endings = ['st','nd','rd'] +17 * ['th'] \

+ ['st','nd','rd'] + 7 *['th'] \

+ ['st']

year = raw_input('Year:')

month = raw_input('Month(1-12):')

day = raw_input('Day (1-31):')

month_number = int(month)

day_number = int(day)

 

#To months and days minus 1,in order to obtain the correct index

month_name =months[month_number-1]

ordinal = day +endings[day_number-1]

print "%s %s,%s"  % (month_name,ordinal,year)

 

學習過程中如果問題,請留言。更多內容請加:
學神IT-linux講師-RM老師QQ:2805537762
學神IT-戚老師QQ:3341251313
學神IT-旭斌QQ:372469347
學神IT教育RHEL7交流羣:468845589



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章