python系列 文件操作的代码

yipeiwu_com6年前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, 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]]) 

好了这篇文章先介绍到这,后续【听图阁-专注于Python设计】小编会为大家分享更多的资料。

相关文章

Python中函数参数调用方式分析

本文实例讲述了Python中函数参数调用方式。分享给大家供大家参考,具体如下: Python中函数的参数是很灵活的,下面分四种情况进行说明。 (1) fun(arg1, arg2, .....

对pandas的行列名更改与数据选择详解

对pandas的行列名更改与数据选择详解

记录一些pandas选择数据的内容,此前首先说行列名的获取和更改,以方便获取数据。此文作为学习巩固。 这篇博的内容顺序大概就是: 行列名的获取 —> 行列名的更改 —> 数据...

Python中logging模块的用法实例

本文实例讲述了logging模块的用法实例,分享给大家供大家参考。具体方法如下: import logging import os log = logging.getLogg...

对TensorFlow中的variables_to_restore函数详解

variables_to_restore函数,是TensorFlow为滑动平均值提供。之前,也介绍过通过使用滑动平均值可以让神经网络模型更加的健壮。我们也知道,其实在TensorFlow...

解读python如何实现决策树算法

数据描述 每条数据项储存在列表中,最后一列储存结果 多条数据项形成数据集 data=[[d1,d2,d3...dn,result], [d1,d2,d3...dn,resul...