Python檔案處理

2021-07-28 11:39:12 字數 2276 閱讀 4717

with

open('pi_digits.txt') as file_object:

contents = file_object.read()

print(contents)

兩個注意點:

filename = 'pi_digits.txt'

with

open(filename) as file_object:

forline

in file_object:

print(line)

儲存到列表中
filename = 'pi_digits.txt'

with

open(filename) as file_object:

lines = file_object.readlines()

forline

inlines:

print(line.rstrip)

儲存到字串中
filename = 'pi_digits.txt'

with

open(filename) as file_object:

lines = file_object.readlines()

pi_string= ''

forline

inlines:

pi_stirng += line.strip()

print(pi_string)

print(len(pi_string))

注意點:

with open(filename) as file_object:

lines = file_object.readlines()

pi_string= ''

for line in lines:

pi_stirng += line.strip()

birthday = input('enter your birthday, in

the form mmddyy:')

if birthday in pi_string:

thefirst million digits of

pi!')

else:

print('your birthday does

thefirst million digits of

pi.')

filename = 'numbers.json'

with

open(filename) as f_obj:

numbers = json.load(f_obj)

print(numbers)

improt json

filename = 'programing.txt'

with

open(filename, 'w') as file_object:

file_object.write("i love programming")

improt json

numbers = [2,3,5,7,11,13]

filename = 'numbers.json'

with

open(filename, 'w') as f_obj:

json.dump(numbers, f_obj)

很多初學者都沒有在程式中寫異常的意識,這會給程式帶來很多危險,比如程式突然崩潰,攻擊者可能會根據traceback對**發起攻擊,一般在涉及到資料互動,輸入輸出等地方,都要寫異常處理語句。寫法如例:

print("give me two numbers, and i'll devide them.")

print("enter 'q' to quit.")

while

true:

first_number = input(\nfirst number:)

if first_number == 'q':

break

second_number = input(\nsecond number:)

try:

answer = int(first_number) / int(second_number)

except zerodivisionerror:

print("you can't dividee by 0!")

else:

pirnt(answer)

python檔案處理

def cal input input.txt output output.txt cal方法為主程式,推薦這樣做而不是python.exe xx.py 預設引數為python目錄的兩個txt,如為其他檔案自己指定。infile file input,r 開啟源資料檔案 outfile file o...

python 檔案處理

1.開啟檔案 open a.txt 當前目錄下的a.txt open root a.txt 開啟某個目錄下的檔案 2.按行顯示檔案 a open a.txt a.readline ni hao n a.readline wo xianzai hen xiang ni n a.readline ni ...

Python檔案處理

open name mode buf read size readline size readlines size 這裡的size是指,io定義的default buffer size為單位大小 iter 迭代器迭代每行 write str writelines sequwence of strin...