python系列 文件操作的代碼
核心代碼
import numpy as np
import os,sys
#獲取當(dāng)前文件夾,并根據(jù)文件名
def path(fileName):
p=sys.path[0]+'\\'+fileName
return p
#讀文件
def readFile(fileName):
f=open(path(fileName))
str=f.read()
f.close()
return str
#寫(xiě)文件
def writeFile(fileName,str):
f=open(path(fileName),'w')
f.write(str)
f.close()
def str1():
str=','.join('我在中國(guó)大地上驕傲地生長(zhǎng)著!')
return str
def str2():
return str(np.random.randint(-49,50,[3,3,3]))
#實(shí)驗(yàn)1
def test_1():
fileName='中國(guó)大地.txt'
writeFile(fileName,str1())
list=readFile(fileName).split(',')
print(list)
#實(shí)驗(yàn)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()
下面是一些
打開(kāi)和關(guān)閉示例:

讀取


寫(xiě)入


randint(low[,high,shape]) 根據(jù)shape創(chuàng)建隨機(jī)整數(shù)或整數(shù)數(shù)組,范圍是[low, high)
numpy.random.randint的詳細(xì)用法
函數(shù)的作用是,返回一個(gè)隨機(jī)整型數(shù),范圍從低(包括)到高(不包括),即[low, high)。如果沒(méi)有寫(xiě)參數(shù)high的值,則返回[0,low)的值。
numpy.random.randint(low, high=None, size=None, dtype='l')
參數(shù)如下:
| 參數(shù) | 描述 |
|---|---|
| low: int | 生成的數(shù)值最低要大于等于low。 (hign = None時(shí),生成的數(shù)值要在[0, low)區(qū)間內(nèi)) |
| high: int (可選) | 如果使用這個(gè)值,則生成的數(shù)值在[low, high)區(qū)間。 |
| size: int or tuple of ints(可選) | 輸出隨機(jī)數(shù)的尺寸,比如size=(m * n* k)則輸出同規(guī)模即m * n* k個(gè)隨機(jī)數(shù)。默認(rèn)是None的,僅僅返回滿足要求的單一隨機(jī)數(shù)。 |
| dtype: dtype(可選): | 想要輸出的格式。如int64、int等等 |
輸出:
返回一個(gè)隨機(jī)數(shù)或隨機(jī)數(shù)數(shù)組
例子
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])
>>>np.random.randint(2, high=10, size=(2,3))
array([[6, 8, 7],
[2, 5, 2]])
好了這篇文章先介紹到這,后續(xù)腳本之家小編會(huì)為大家分享更多的資料。
相關(guān)文章
tensorflow使用tf.data.Dataset 處理大型數(shù)據(jù)集問(wèn)題
這篇文章主要介紹了tensorflow使用tf.data.Dataset 處理大型數(shù)據(jù)集問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
完美解決Django2.0中models下的ForeignKey()問(wèn)題
這篇文章主要介紹了完美解決Django2.0中models下的ForeignKey()問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
Python實(shí)現(xiàn)計(jì)算圖像RGB均值方式
這篇文章主要介紹了Python實(shí)現(xiàn)計(jì)算圖像RGB均值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
python docx段落對(duì)齊實(shí)現(xiàn)方式
python-docx庫(kù)是一個(gè)用于創(chuàng)建和更新MicrosoftWord文檔的庫(kù),提供了豐富的功能,包括段落對(duì)齊方式設(shè)置,段落對(duì)齊方式可以通過(guò)Paragraph對(duì)象的alignment屬性來(lái)設(shè)置,常用的對(duì)齊方式包括左對(duì)齊、右對(duì)齊、居中對(duì)齊、兩端對(duì)齊等2024-11-11
Python實(shí)現(xiàn)json對(duì)值進(jìn)行模糊搜索的示例詳解
我經(jīng)常使用json進(jìn)行存儲(chǔ)配置,于是常常遇到這樣的問(wèn)題:如果想要對(duì)某個(gè)數(shù)組里的值進(jìn)行模糊搜索,同時(shí)輸出相關(guān)的其他數(shù)組相同位置的的值該如何實(shí)現(xiàn)呢?本文就來(lái)和大家詳細(xì)聊聊2023-01-01
python實(shí)現(xiàn)爬取圖書(shū)封面
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)爬取圖書(shū)封面的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07

