Python基礎學習的一些記錄

2021-09-28 19:38:58 字數 2575 閱讀 1161

file1 =

open

('/users/baoxiao/desktop/test/score.txt'

,'r'

,encoding=

'utf-8'

)# readlines() 會從txt檔案取得乙個列表,列表中的每個字串就是scores.txt中的每一行。

# 而且每個字串後面還有換行的\n符號。

filelines = file1.readlines(

)file1.close(

)for i in filelines:

# 本身字串自帶換行,但讀取時任然是一串連線的字元,

data=i.split(

)print

(data)

python使用open()函式讀取檔案,這裡使用readline()將檔案中每一行當做乙個元素存入列表,然後遍歷列表,使用split()來分隔每乙個元素並輸出,這樣將返回i個列表,每個列表是原來那一行的內容。

同樣還有join()方法,合併元素內容。

```pythona=[

'c',

'a',

't']

b=''

print

(b.join(a))c=

'-'print

(c.join(a)

)

輸出結果是

catc-a-t

```python

file1 = open('/users/baoxiao/desktop/test/score.txt', 'r', encoding='utf-8')

# readlines() 會從txt檔案取得乙個列表,列表中的每個字串就是scores.txt中的每一行。

# 而且每個字串後面還有換行的\n符號。

filelines = file1.readlines()

file1.close()

final_score=

for i in filelines:

# 本身字串自帶換行,但讀取時任然是一串連線的字元,

data=i.split()

sum=0

for score in data[1:]:

sum=sum+int(score)

result=data[0]+str(sum)

print(result)

winnner=open('/users/baoxiao/desktop/test/winner.txt','w',encoding='utf-8')

# 按行輸入最終的結果

winnner.writelines(final_score)

winnner.close()

改進版對資料進行求和輸出。

輸出資料時,若沒有原始檔案,則自動生成原始檔案,由於write()只可以寫入乙個字串,而writelines()可以寫入乙個列表,為了匹配寫入型別,使用writelines().

print

('吳楓'

.encode(

'utf-8'))

print

('吳楓'

.encode(

'gbk'))

print

(b'\xe5\x90\xb4\xe6\x9e\xab'

.decode(

'utf-8'))

print

(b'\xce\xe2\xb7\xe3'

.decode(

'gbk'))

print

(type

('吳楓'))

print

(type

(b'\xce\xe2\xb7\xe3'

))

小玩具,十六進製制和中文字元之間的裝換

list_test =

['一弦一柱思華年。\n'

,'只是當時已惘然。\n'

]# 將要默寫的詩句放在列表裡。

with

open

('/users/baoxiao/desktop/test/test2_15/poem1.txt'

,'r'

)as f:

lines = f.readlines(

)print

(lines)

with

open

('/users/baoxiao/desktop/test/test2_15/poem1.txt'

,'w'

)as new:

for line in lines:

if line in list_test:

# 屬於默寫列表中的句子,將其替換成橫線。

new.write(

'____________。\n'

)else

: new.write(line)

第乙個指令碼,用於獲取檔案,並修改檔案。改進版就可以製作成古詩默寫試卷,每一次只要更改list_test裡的內容即可,下乙個思考點,新建乙個檔案,讀取為列表,然後隨機選取默寫的內容並生成新的試卷。

學習python的一些基礎普及

我很納悶,為什麼連python這樣的開源 國內對它的官網要遮蔽掉,簡直匪夷所思!不知道是不是我的dns服務商的問題。python 官網 有時候這官網能上,有時候卻不能被遮蔽掉了。包含了各個版本python 以及python的安裝包,原始碼包和chm幫助文件 中文幫助文件,推薦入門級的看這裡 pyth...

學習python遇到的一些函式記錄

help 利用help 函式名 可以找到函式的幫助文件,裡面有這個函式引數的使用說明 如help numpy.genfromtxt pandas.value counts parameters values ndarray 1 d sort boolean,default true sort by ...

初學python時一些基礎內容記錄

if連續判斷 1 年齡小於18,童工 2 年齡18到65,合法員工 3 年齡大於65,退休員工 age int input 請輸入您的年齡 if age 18 yuangong type 童工 elif age 18 and age 65 yuangong type 合法員工 else yuango...