python中os和sys模块的使用

【Python案例】(一)os和sys模块 文章目录OS模块1. 查询当前模块及路径下文件2. 返回绝对路径3. 查看路径的文件夹部分和文件名部分4. 查看文件时间5. 查看文件大小6. 删除和创建目录或文件7. 查看文件是否存在8. 获取路径(os和sys的区别)sys模块sys模块常用方法 OS模块 os 源于英文Operating System(操作系统)的缩写 1. 查询当前模块及路径下文件 os.getcwd():得到当前工作目录,即当前python脚本工作的目录途径 cwd: Current Working Directory 阅读详情

python内置库os和sys模块非常有用,在对系统或操作系统的操作方面都很有用,比如判断一个文件是否是目录,一个路径是否存在,获取系统的编码等等。

1.os包:os包下可以直接调用的函数

getcwd:  获取当前工作目录路径,无参,返回 字符串

listdir: 获取指定路径下所有的文件和文件夹,参数是path, 返回 列表

makedirs: 创建多级文件夹,如果没有给绝对路径,会创建到当前路径(相对路径),参数是path mode.

示例:

def os_func():
    
    curr_path = os.getcwd()
    print('当前工作路径:', curr_path)
    
    new_path = '%s/test2' % curr_path
    if os.path.exists(new_path):
        print('file with the given path exists.')
    else:
        os.makedirs(new_path)
    
    data = os.listdir(curr_path)
    print(data)

    new_path2 = '%s/test2/abc' % curr_path  # 已存在的文件再新建文件,会报错
    os.makedirs(new_path2)

    # 没有给路径,只给了一个文件/文件夹,就直接在当前路径下新建文件
    os.makedirs('test3')  
输出:

FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'C:\\Users\\fang\\PycharmProjects\\pyProj\\basic2/test2/abc'

current path:  C:\Users\fang\PycharmProjects\pyProj\basic2
['basic_lx.py', 'dt1.txt', 'os_func2.py', 'os_funcs.py', 'tes.txt', 'test11', 'test2', 'time_lx.py', '__init__.py']

如上,如果已存在的文件路径,再创建文件,那么会报错’当文件已存在时,无法创建该文件。‘

removedirs: 传参path, 删除给定路径的多级文件夹,

rename(oldname, newname): 重命名文件/文件夹,

rmdir: 只删除空文件夹,传参空目录,如果是非空,则无法删除

例子:

def os_func2():
    
    if os.path.exists('test2'):
        os.removedirs('test2')
    
    os.rmdir('test3')
    os.rename('test11', 'test1')

输出:
 File "C:\Users\fang\PycharmProjects\pyProj\basic2\os_func2.py", line 37, in os_func2
    os.removedirs('test2')
  File "C:\Users\fang\AppData\Local\Programs\Python\Python310\lib\os.py"
python的os模块详细解读 os是“operating system”的缩写,os模块提供各种 Python 程序与操作系统进行交互的接口,使用os模块,一方面可以方便地与操作系统进行交互,另一方面页可以极大增强代码的可移植性 阅读详情

相关推荐

〖Python零基础入门篇㊾〗- Python中的 os 包

今天我们来学习一下 python 的内置包 —> OS 包。OS 包拥有着普遍的操作系统功能,拥有着各种各样的函数来操作系统的驱动功能。其中最常用的就是对 路径 与 文件的操作,比如检查某个路径下是否存在某个文件,某个路径是否存在等。也可以创建、删除文件等,接下来我们就详细的看一看 OS 中关于文件的操作功能与用法。

易编橙 · 终身成长社群,相遇已是上上签! 4万+

别再手动敲代码了!用STM32CubeMX+FreeRTOS图形化配置,5分钟搞定多任务通信框架

本文详细介绍了如何利用STM32CubeMX和FreeRTOS快速搭建多任务通信框架,大幅提升嵌入式开发效率。通过图形化配置工具,开发者可在5分钟内完成任务调度、时钟配置和内核对象生成,特别适合物联网设备开发。文章还提供了代码优化和调试技巧,帮助开发者轻松应对复杂应用场景。

weixin_30363285的博客 291

Android11,无障碍服务模拟多手势使用dispatchGesture时总是onCancelled

AccessibilityService的dispatchGesture去模拟多手势,总是onCancelled的一种解决办法

m0_49953943的博客 2102

【学习笔记】人群归因分数 PAF 以及combined PAF

人群归因风险比例(Population Attributable Fraction,PAF)是一个流行病学指标,它估计了在总体中,如果能消除一个特定的危险因素,能预防多少百分比的疾病或健康结果。简单来说,PAF回答的是:“如果没有这个风险因素,总体中会有多少病例是可以避免的?

weixin_53499537的博客 4900

TCS34725颜色识别模块实战调校:从“一坨”例程到精准RGB

本文针对TCS34725颜色识别模块初始数据不准的问题,提供了从基础例程到精准调校的实战指南。核心在于通过白光校正与黑白光校正两种方法,补偿传感器偏差与环境光影响,将原始数据准确映射为标准RGB值。文章详细阐述了校准原理、操作步骤与代码实现,并分享了进阶调试技巧与避坑指南,帮助开发者显著提升颜色识别的准确性与项目可靠性。

weixin_29188043的博客 289

线性代数笔记【空间曲面】

二次曲面 曲面可以看成是一个动点或一条动曲线按照一定条件或规律运动产生的轨迹 曲面的方程即是该动点的坐标所满足的方程 空间解析几何中,一般会涉及到由曲面写方程和由方程看曲面两种类型问题 曲面与曲面方程 球面方程 球面:空间内与定点的距离等于定长的点的集合 这一定点叫球心,定长叫半径 标准方程 (x−x0)2+(y−y0)2+(z−z0)2=r2(x-x_0)^2+(y-y_0)^2+(z-z_0)^2=r^2(x−x0​)2+(y−y0​)2+(z−z0​)2=r2 球心P0(x0,y0,z0)P_0(

qq_40500005的博客 3246

(一)Tushare Pro教程:股票基本数据接口

 一直使用tushare作数据源,这里开个教程大家一起学习。 一、介绍        tushare是一个python股票数据源,现已升级到tushare pro版本,新版本在数据稳定性和获取速率上大幅提升。与wind、东财等收费数据源相比,tushare pro算是金融数据界的良心之作,其为从事金融工程、量化研究等方向的同学们提供了便利。tushare pro还有一点突出的特色就是已经将股票...

虎毛的博客 4万+

深入了解BPM及BPM业务流程管理系统

BPM 即业务流程管理,是一种以规范化的构造端到端的卓越业务流程为中心,以持续地提高组织业务绩效为目的的系统化方法。它涵盖了业务流程的整个生命周期,包括流程的设计、执行、监控、分析和优化。BPM 作为一种先进的管理方法,对于企业提高运营效率、降低成本、提升客户满意度和增强竞争力具有重要意义。BPM 流程管理系统为企业实现 BPM 提供了强大的工具和支持,而 F2BPM 流程管理平台以其先进的技术架构、丰富的功能模块、简单易用的操作界面和强大的定制能力,成为企业实现业务流程管理的理想选择。

Stone3625的博客 2952

【图像增强(Image Enhancement )】专栏的相关说明,包含适配人群、专栏简介、专栏亮点、阅读方法、定价理由、品质承诺、关于更新、关于答疑、文章目录、与我联系等(持续更新中...)

专栏内涉及的算法都是基于深度学习的图像增强算法;收录的文章基本上是基于Pytorch框架实现的,部分基于Tensorflow;预计完成100篇论文,并持续更新;专栏内文章主要为两部分:【论文精读】与【论文复现】论文精读:读懂论文,总结提炼,聚焦核心内容,不只是全文翻译论文复现:跑通流程,源码解析,提升代码能力,得到去噪结果以及指标计算综合而言,从大到小拆解模型结构,从小到大实现模型搭建。实现论文与源码的统一,深入理解论文行文逻辑与代码实现逻辑,融汇贯通二者思想,并学以致用。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 4054

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

上一篇: python读写文件的三种做法
下一篇: python中datetime模块时间的使用
幸运的星竹
博客等级 码龄11年 190粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值