「笨辦法」學Python3 習題20 函式和檔案

2021-09-24 15:44:02 字數 1706 閱讀 4078

目錄

函式與檔案

print後不自動換行

from sys import ar**

script,input_file = ar**

def print_all(f):

print(f.read())

def rewind(f):

f.seek(0)

def print_a_line(line_count,f):

print(line_count,f.readline())

current_file = open(input_file)

print("first let's print the whole file:")

print_all(current_file)

print("let's rewind ,kind of like a tape.")

rewind(current_file)

print("let's ptint three lines:")

current_line = 1

print_a_line(current_line,current_file)

current_line = 1+current_line

print_a_line(current_line,current_file)

current_line = 1+current_line

print_a_line(current_line,current_file)

python裡的檔案就像磁帶/***一樣,有乙個用來讀取資料的「磁頭」,可以通過它來操作檔案,每次執行f.seek(0)就回到了檔案的起始位置,而f.readline()則會讀取檔案的一行,然後把「磁頭」移動到\n的後面去。

from sys import ar**

script,input_file = ar**

def print_all(f):

print(f.read())

def rewind(f):

f.seek(0)

def print_a_line(line_count,f):

print(line_count,f.readline(),end="")#print新增引數end=「」,不會自動換行了

current_file = open(input_file)

print("first let's print the whole file:")

print_all(current_file)

print("let's rewind ,kind of like a tape.")

rewind(current_file)

print("let's ptint three lines:")

current_line = 1

print_a_line(current_line,current_file)

current_line = 1+current_line

print_a_line(current_line,current_file)

current_line = 1+current_line

print_a_line(current_line,current_file)

笨辦法學Python 3 習題6

交作業啦 ex6.py 建立了乙個名叫types of people的變數,並將其設為等於10 types of people 10 建立了乙個名叫x的變數,並將其設為f string x f there are types of people.建立了乙個名叫binary的變數,並將其設為字串 bi...

《笨辦法學Python》 習題3

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 print i will now count my chickens print hens 25 30 6.0 print roosters 100 25 3 4 print now i wil...

《笨辦法學python》習題38 40

mystuff 然後作者又給出了乙個錯誤的情況 class thing object def test hi print hia thing a.test hello 錯誤原因是test 只可以接受乙個引數,卻給了兩個。也就是 a.test hello 實際上是test a,hello 從這裡開始到...