1. 程式人生 > >python學習_22(文件)

python學習_22(文件)

app 符號 and con pri 大於 scrip multi truncate

1?寫一個函數,實現遍歷一個數字和字母參雜的字符串,如果碰到字母則替換成,最後隔開的數字作為整體計算求和。
如”ab34aa243dd78eww89”,則替換成的結果為:”342437889”,求和結果為:”791517”

s=?"ab34aa243dd78eww89"
result?=""
count?=0
flag=False
for?i?in?s:
????if?i>=‘a‘?and?i<="z":
????????if?flag=True:
????????????result+=str(count)
????????????flag=False
????????????count=0
????????result+="*"
????else:
????????flag=True
????????count+=int(i)

result+=str(count)

print?(result)
#?encoding?=?UTF-8
import?re
s=?"ab34aa243dd78eww89"
result?=""

s=re.sub(r"[a-z]","*",s)?
arr1=re.split("\\*+",s)?#[‘‘,?‘34‘,?‘243‘,?‘78‘,?‘89‘]
for?i?in?range(len(arr1)):
????count=0
????if?arr1[i].isdigit():
????????for?j?in?arr1[i]:
????????????count+=int(j)
????if?count!=0:
????????arr1[i]?=?str(count)

arr2=re.split("\\d+",s)#[‘**‘,?‘**‘,?‘**‘,?‘***‘,?‘‘]

for?i?in?range(len(arr1)):
????result+=arr1[i]+arr2[i]

print(result)
#?encoding?=?UTF-8
import?re
s=?"ab34aa243dd78eww89"
result?=""

s=re.sub(r"[a-z]","*",s)?
arr1=re.split("\\*+",s)?#[‘‘,?‘34‘,?‘243‘,?‘78‘,?‘89‘]
for?i?in?range(len(arr1)):
????count=0
????if?arr1[i].isdigit():
????????for?j?in?arr1[i]:
????????????count+=int(j)
????if?count!=0:
????????arr1[i]?=?str(count)

arr2=re.split("\\d+",s)#[‘**‘,?‘**‘,?‘**‘,?‘***‘,?‘‘]

for?i?in?range(len(arr1)):
????result+=arr1[i]+arr2[i]

print(result)

2?一個字符串i?am?learning,請依照如下規則轉換為數字
abcd–5,?efgh–10,?ijkl–15,?mnop–20,?qrst–25,?uvwx–30?yz–35
轉換正確結果為:15?520?151052520152010

rule="abcd–5,efgh–10,ijkl–15,mnop–20,qrst–25,uvwx–30,yz–35"
rule=rule.split(",")
s="i?am?learning"
result=""
for?i?in?s:
????for?r?in?rule:
????????if?i?in?r:
????????????#print?(r.split("–"))
????????????part=r.split("–")[-1]
????????????#print?("part",part)
????????????result?+=part
????????????#print(result)
????????????break
????else:
????????result+=i

print?(result)

3?從控制臺輸入一串字母,判斷是否是連續相同字母,是則輸出True,否則輸出False。

def?judge_str():
????s=input("請輸入一串字符串")
????
????if?s[0]*len(s)==s?and?((s[0]>=‘a‘?and?s[0]<=‘z‘)?or?(s[0]>=‘A‘?and?s[0]<=‘Z‘)):
????????return?True
????else:
????????return?False

print?(judge_str()) 

open()函數
open() 方法用於打開一個文件,返回文件對象

語法格式:
open(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
參數說明:
file:文件名稱
mode:指定文件的打開方式,其中,‘rt‘為默認方式(t也就是text,代表文本文件)
encoding:編碼或者解碼方式。默認編碼方式依賴平臺,如果需要特殊
設置,可以參考codecs模塊,獲取編碼列表。encoding不寫的話默認用的是GBK
?newline:換行控制,參數有:None,‘\n‘,‘\r‘,‘\r\n。為None的話,寫‘\r’‘\r\n’‘\n’的話全部轉換成‘\n’

文件打開方式
1、直接通過open打開

>> fp = open("e:\python\a.txt")
>> print(fp)
<_io.TextIOWrapper name=‘e:\python\a.txt‘ mode=‘r‘ encoding=‘cp936‘>

>> fp = open("e:\python\a.txt")
>> fp.read()

UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xbf in position 2: illegal multibyte sequence

>> fp = open("e:\python\a.txt",encoding="utf8")
>> fp.read()
‘\ufeff((1,2,3),("a","b","c"),("a",1,2))\n(6, \‘abc\‘, False)‘

文件默認打開方式是gbk編碼,文件打開的編碼需要和文件保存編碼一致
如果文件本身以ANSI 保存可以使用默認編碼,不指定encoding編碼
如果文件以utf-8保存,需要執行encoding為utf8編碼,不指定會報錯

2、通過with語句打開

>> with open("e:\python\a.txt") as file_obj:
... print(file_obj.read())
...
關閉文件
通過open直接打開的文件需要手動關閉,with方式打開的會自動關閉
>> fp = open("e:\python\a.txt",encoding="utf8")
>> fp.read()
‘\ufeff((1,2,3),("a","b","c"),("a",1,2))\n(6, \‘abc\‘, False)‘
>> fp.close()

讀取文件
read([size])
size為讀取的長度,以byte為單位。如果不指定參數,表示一次性讀取全部內容,以字符串形式返回,並且每一行結尾會有一個"\n"符號;
指定size返回size字節內容

>> with open("e:\python\a.txt") as file_obj:
... print(file_obj.read())
...

>> fp = open("e:\python\a.txt",encoding="utf8")
>> fp.read(1)
‘a‘
>> fp.read(2)
‘bc‘
>> fp.tell()
3

readline([size])
如果不指定size參數,每次讀取一行內容,返回字符串,讀取後文件指針跳到下一行
如果指定size,size小於一行的字節數,返回該行size字節字符,大於等於一行字節數返回該行內容

>> fp.readline(2)
‘ab‘
>> fp.readline(3)
‘c12‘
>> fp.readline()#只返回剩余字節字符
‘3456789\n‘
>> fp.readline(50)
‘xyz\n‘
>> fp.readline()
‘aaaaaaaa\n‘

readlines([size])
不指定size參數返回文件每行內容組成的列表,列表的每個元素是字符串且結尾有個\n換行符,讀取後文件指針在文件末尾
指定參數size:
當時size參數為0 或大於等於文件所有字節數時 返回全部文件內容組成的列表
當size小於一行文件內容時,返回該行內容
當size大於1行大小,小於兩行大小時候返回2行
。。。。。

文件內容:
abc
xyz
aaaa

>> fp = open("e:\python\a.txt")
>> fp.readlines(0)
[‘abc\n‘, ‘xyz\n‘, ‘aaaa‘]
>> fp.seek(0,0)
0
>> fp.readlines(2)
[‘abc\n‘]
>> fp.seek(0,0)
0
>> fp.seek(0,0)
0
>> fp.readlines(5)
[‘abc\n‘, ‘xyz\n‘]
>> fp.seek(0,0)
0
>> fp.readlines(8)
[‘abc\n‘, ‘xyz\n‘, ‘aaaa‘]

>> fp = open("e:\python\a.txt")
>> for i in range(10):
... print(fp.readlines(i))
... fp.seek(0,0)
...
[‘abc\n‘, ‘xyz\n‘, ‘aaaa‘]
0
[‘abc\n‘]
0
[‘abc\n‘]
0
[‘abc\n‘]
0
[‘abc\n‘, ‘xyz\n‘]
0
[‘abc\n‘, ‘xyz\n‘]
0
[‘abc\n‘, ‘xyz\n‘]
0
[‘abc\n‘, ‘xyz\n‘]
0
[‘abc\n‘, ‘xyz\n‘, ‘aaaa‘]
0
[‘abc\n‘, ‘xyz\n‘, ‘aaaa‘]
0

寫文件
write([str])
write()?方法用於向文件中寫入指定字符串。返回寫入的字符數,會移動相應的文件指針
在文件關閉前或緩沖區刷新前,字符串內容存儲在緩沖區中,這時你在文件中是看不到寫入的內容的。
如果文件打開模式帶 b,那寫入文件內容時,str (參數)要用 encode 方法轉為 bytes 形式,否則報錯:TypeError: a bytes-like object is required, not ‘str‘。

寫入的類型必須是字符串

>> with open("e:\python\aa.txt","w") as file_obj:
... file_obj.write("testwrite")
...
9
>> with open("e:\python\aa.txt","w") as file_obj:
... file_obj.write("中國")
...
2

writelines(seq)
writelines()?方法用於向文件中寫入一序列的字符串。可寫入列表、元組、字符串,序列中的內容必須是字符串,寫入後文件指針在文件末尾

>> content = ["abc\n","xyx\n","123"]
>> with open("e:\python\aa.txt","w",encoding="utf8") as file_obj:
... file_obj.writelines(content)
...

>> content = ("abcd\n","xyx\n","123")
>> with open("e:\python\aa.txt","w",encoding="utf8") as file_obj:
... file_obj.writelines(content)
...
>> tstr = "a\nb\c"
>> with open("e:\python\aa.txt","w",encoding="utf8") as file_obj:
... file_obj.writelines(tstr)
...

file.closed 返回true如果文件已被關閉,否則返回false。
file.mode 返回被打開文件的訪問模式。
file.name 返回文件的名稱。

>> fp = open("e:\python\a.txt")
>> fp.name
‘e:\python\a.txt‘

>> fp.mode
‘r‘

>> fp.closed
False

文件常用操作方法:
close()
File 對象的 close()方法刷新緩沖區裏任何還沒寫入的信息,並關閉該文件,這之後便不能再進行寫入

>> fp = open("e:\python\a.txt")
>> fp.read()
‘abc\nxyz\naaaa‘
>> fp.close()
>> print("文件是否關閉: ",fp.closed)
文件是否關閉: True

flush()
該函數是將緩沖區中的內容寫入硬盤。

>> fp = open("e:\python\1008.txt","w+")
>> fp.write("1009")
4
>> fp.flush()
>> fp.close()

fileno()
返回一個整型的文件描述符(file descriptor FD 整型),可用於底層操作系統的 I/O 操作。

>> fp = open("e:\python\a.txt","w+")
>> fp.fileno
<built-in method fileno of _io.TextIOWrapper object at 0x0000000000388B40>
>> fp.fileno()
3

isatty()
檢測文件是否連接到一個終端設備,如果是返回 True,否則返回 False。
如果用linux遠程工具 xmanage等打開文件

>> fp.isatty()
False

tell()
返回文件的當前位置,即文件指針當前位置

>> fp = open("e:\python\a.txt")
>> fp.read(1)
‘‘
>> fp.close()
>> fp = open("e:\python\a.txt")
>> fp.read(1)
‘a‘
>> fp.tell()
1
>> fp.readline()
‘bc\n‘
>> fp.tell()
5
>> fp.readlines()
[‘xyz\n‘, ‘aaaa‘]
>> fp.tell()
14

seek( offset[, from ] )
seek(offset [,from])這是一個文件定位函數,該方法改變當前文件的位置。Offset變量表示要移動的字節數。From變量指定開始移動字節的參考位置。
如果from被設為0(默認值),這意味著將文件的開頭作為移動字節的參考位置。
如果設為1,則使用當前的位置作為參考位置。
如果它被設為2,那麽該文件的末尾將作為參考位置。需要註意,如果文件以a或a+的模式打開,每次進行寫操作時,文件操作標記會自動返回到文件末尾

模式1、模式2只能用於二進制模式

>> fp = open("e:\python\a.txt")
>> fp.seek(1,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can‘t do nonzero cur-relative seeks

>>?import?os
>>?os.linesep
‘\r\n‘
>>?fp?=?open("e:\a.txt","w")
>>?fp.write("a\r\nb\rc\nd")
8
>>?fp.close()
>>?fp?=?open("e:\a.txt","r")
>>?fp.read()
‘a\n\nb\nc\nd‘

a 模式打開 文件指針在最後
讀寫文件指針都會移動

利用readline()讀取所有行

>>?fp?=?open("e:\a.txt","r")
>>?while?1:
...?????content?=?fp.readline()
...?????print?(content)
...?????if?content?=="":
...?????????break
...
hello?world!1

hello?world!2

hello?world!3

hello?world!4

>>?fp.close()

#encding=utf-8

fp?=?open(?"c:\downloads\ip1.txt",‘w‘)
print?("文件是否關閉:",?fp.closed)
print?("文件的訪問模式:",?fp.mode)
print?("文件名稱:",?fp.name)
#關閉文件
fp.close()

>> fp = open("e:\python\1.txt")
>> fp.read(5)
‘hhqhh‘
>> fp.tell()
5
>> fp.read(1)
‘h‘
>> fp.tell()
6

>> fp.readline(3)
‘hhh‘
>> fp.seek(0,0)
0
>> fp.readline(4)
‘hhqh‘

>> fp.seek(0,0)
0
>> fp.readlines(2)
[‘hhqhhhhhhh\n‘]

習題:一個文件寫入
a26
b25
c24
d23
e22
f21
g20
h19
i18
j17
k16
l15
m14
n13
o12
p11
q10
r9
s8
t7
u6
v5
w4
x3
y2
z1

with open("e:\python\0923.txt","w",encoding="utf8") as file_obj:
n = 26
for i in range(97,123):
file_obj.write(chr(i)+str(n)+"\n")
n -= 1
with?open("e:\a.txt",‘w+‘)?as?fp:
????for?i?in?range(26):
????????fp.write(chr(ord("a")+i)+str(26-i)+"\n")
????fp.seek(0,0)
????print?(fp.read())

writelines

flush()

>> fp1 = open("e:\python\2.txt")
>> fp1.fileno()
3

>> fp1.isatty()
False

tell()

練習:
遊標的第5個位置,第一次寫a,讀出來
第二次寫b,讀出來
讀出來第二行的一個遊標位置的內容

with open("e:\\python\\2.txt","r+",encoding="utf8") as file_obj:
    file_obj.seek(5,0)
    file_obj.write("a")
    file_obj.seek(5,0)
    print(file_obj.read(1))

    file_obj.seek(5,0)
    file_obj.write("b")
    file_obj.seek(5,0)
    print(file_obj.read(1))

    file_obj.seek(0,0)
    file_obj.readline()

    print(file_obj.read(1))

習題:文件中有兩行內容,你在中間再加入一行

with open("e:\\python\\2.txt","r+",encoding="utf8") as file_obj:
    content = file_obj.readlines()
    content.insert(1,"xyyyyyyyy\n")
with open("e:\\python\\2.txt","w",encoding="utf8") as file_obj:
    file_obj.writelines(content)

with open("e:\\python\\2.txt","r+",encoding="utf8") as file_obj:
    content = file_obj.readlines()
    content.insert(1,"xyyyyyyyy\n")
    file_obj.seek(0,0)
file_obj.writelines(content)

fp1 = open("e:\c.txt","w+",encoding="utf8")
fp1.write("123\n")
fp1.write("456\n")

fp1.seek(0,0)
print(fp1.readline())
print(fp1.tell())
fp1.write("abcdfdfd\n")

fp1.seek(0,0)
print(fp1.readlines())
fp1.close()

Seek() 1 ,2只能在二進制模式下使用

>>?fp?=?open("e:\a.txt","rb+")
>>?fp.read()
b‘1234aaxxx\r\ngloryroad\r\nbxxxx\r\n‘
>>?fp.tell()
29
>>?fp.seek(5,1)
34
>>?fp.seek(-5,1)
29
>>?fp.seek(-5,1)
24
>>?fp.read()
b‘xxx\r\n‘
>>?fp.seek(-5,1)
24
>>?fp.seek(2,1)
26
>>?fp.read()
b‘x\r\n‘
>>

>> fp = open("e:\python\1.txt","rb")
>> print(fp.read())
b‘hhqhhhhhhh\r\ns\r\ns\r\ns\r\ns\r\ns\r\ns‘
>> fp.seek(-3,1)
25
>> print(fp.read())
b‘\r\ns‘
>> fp.seek(-3,2)
25
>> print(fp.read())
b‘\r\ns‘
>> fp.seek(-3,2)
25
>> fp.readline()
b‘\r\n‘
>> fp.seek(0,0)
0
>> print(fp.read())
b‘hhqhhhhhhh\r\ns\r\ns\r\ns\r\ns\r\ns\r\ns‘
>> fp.seek(0,0)
0
>> fp.seek(-8,2)
20
>> print(fp.read())
b‘\ns\r\ns\r\ns‘
>>

讀取指定行:

>>?count=0
>>?for?line?in?fp:
...?????count+=1
...?????if?count?==2:
...?????????print(line)
...
b‘gloryroad\r\n‘

print(fp.readlines()[1])

截取文件為指定字節大小

>> fp = open("e:\python\2.txt","r+")
>> fp.truncate(5)
5

#清理緩存,如果你不再需要先前從getline()中得到的行
linecache.clearcache()

判斷空行
line.strip() == “”

fp=open("e:\\a.txt","r+")
lines=?fp.readlines()
fp.seek(0,0)
for?line?in?lines:
????if?not?line.strip()=="":
????????fp.write(line)

fp.close() 

>> exec("a=100")
>> a
100

python學習_22(文件)