1. 程式人生 > 程式設計 >python系列 檔案操作的程式碼

python系列 檔案操作的程式碼

核心程式碼

import numpy as np
import os,sys

#獲取當前資料夾,並根據檔名
def path(fileName):
 p=sys.path[0]+'\\'+fileName
 return p

#讀檔案 
def readFile(fileName):
 f=open(path(fileName))
 str=f.read()
 f.close()
 return str
 
#寫檔案 
def writeFile(fileName,str):
 f=open(path(fileName),'w')
 f.write(str)
 f.close()

def str1():
 str=','.join('我在中國大地上驕傲地生長著!')
 return str

def str2():
 return str(np.random.randint(-49,50,[3,3,3]))

#實驗1 
def test_1():
 fileName='中國大地.txt'
 writeFile(fileName,str1())
 list=readFile(fileName).split(',')
 print(list)

#實驗2
def test_2():
 writeFile('str1',str1())
 writeFile('str2',str2())
 str_1=readFile('str1')
 str_2=readFile('str2')
 print(str_1)
 print(str_2)
 
test_2()

下面是一些

開啟和關閉示例:

讀取

寫入

randint(low[,high,shape]) 根據shape建立隨機整數或整數陣列,範圍是[low,high)

numpy.random.randint的詳細用法

函式的作用是,返回一個隨機整型數,範圍從低(包括)到高(不包括),即[low,high)。如果沒有寫引數high的值,則返回[0,low)的值。

numpy.random.randint(low,high=None,size=None,dtype='l')
引數如下:

引數 描述
low: int 生成的數值最低要大於等於low。
(hign = None時,生成的數值要在[0,low)區間內)
high: int (可選) 如果使用這個值,則生成的數值在[low,high)區間。
size: int or tuple of ints(可選) 輸出隨機數的尺寸,比如size=(m * n* k)則輸出同規模即m * n* k個隨機數。預設是None的,僅僅返回滿足要求的單一隨機數。
dtype: dtype(可選): 想要輸出的格式。如int64、int等等

輸出:

返回一個隨機數或隨機數陣列

例子

>>> np.random.randint(2,size=10)
array([1,1,0])
>>> np.random.randint(1,size=10)
array([0,0])
>>> np.random.randint(5,size=(2,4))
array([[4,2,1],
[3,0]])
>>>np.random.randint(2,high=10,3))
array([[6,8,7],
[2,5,2]])

好了這篇文章先介紹到這,後續我們小編會為大家分享更多的資料。