1. 程式人生 > 其它 >程序間通訊機制

程序間通訊機制

1.檔案處理

open()

"r,a,w,x"

r:讀取

a:追加,讀取並建立

w:進行寫入

x:建立

f = open("1.txt","rt")

如需開啟檔案,請使用內建的 open() 函式。

open() 函式返回檔案物件,此物件有一個 read() 方法用於讀取檔案的內容:

f = open("demofile.txt", "r")
print(f.read())

返回某一行

f = open("demofile.txt", "r")
print(f.readline())

逐行遍歷檔案

f = open("demofile.txt", "r")
for x in f:
  print(x)
x是一個變數;

關閉檔案

f = open("demofile.txt", "r")
print(f.readline())
f.close()

字串
a = "Hello"
print(a)
多行字串
a = '''Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code.'''
print(a)

函式
呼叫
def my_function():
  print("Hello from a function")

my_function()

引數(函式中會用到的x)
def my_function(fname):
  print(fname + " Gates")

my_function("Bill")
my_function("Steve")
my_function("Elon")

以list傳參
def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

列表

thislist = ["apple", "banana", "cherry"]
print(thislist)
訪問print(thislist【1】)
負的索引

索引範圍
更改值
遍歷列表

py的正則表示式
import re
re.match #從開始位置開始匹配,如果開頭沒有則無

re.search #搜尋整個字串

re.findall #搜尋整個字串,返回一個list