python---文件/目录相关操作、if not text:判断

本文介绍了Python中文件的打开、读写和关闭,强调了文件操作的重要性及文件指针的概念。还讨论了`if not text:`条件的含义,解释了在Python中哪些值被视为False。此外,给出了复制文件的实例,以及使用os模块进行文件和目录管理的基本操作。

文件

在计算机中,文件是以二进制的方式保存在磁盘上的。

文件分为文本文件二进制文件。文本文件本质上也是二进制文件。二进制文件不是直接给人阅读的,比如图片、视频等,而是提供给其他软件使用的。

文件的操作步骤:
1、打开文件
2、读写文件
读:将文件读入内存
写:将内存内容写入文件
3、关闭文件

函数/方法 说明
open 打开文件,并且返回文件操作对象
read 将文件内容读取到内存
write 将制定内容写入文件
close 关闭文件

open函数负责打开文件,并返回文件对象
read/write/close三个方法都需要通过文件对象来调用

file = open("README")
text = file.read()
print(text)
file.close()

文件名区分大小写,打开文件后一定要记得关闭,否则消耗系统资源,并且会影响后续访问。

文件指针标记从哪个位置开始读取数据,第一次打开文件时,通常文件指针会指向文件的开始位置,当执行了read方法后,文件指针会移动到读取内容的末尾。

因此,当read文件一次之后,再次read文件,会读取不到内容。

open函数默认以只读方式打开文件,并且返回文件对象。

语法如下:

f = open("文件名", "访问方式"
### 解决 Conda Terms of Service 未接受问题 您遇到的是 Anaconda 最新的合规性要求。从 2022 年开始,Anaconda 强制要求用户接受其软件仓库的使用条款才能继续使用公共频道。 --- ### 第一步:接受 Terms of Service #### 方案1:逐个接受(推荐) ```powershell # 接受主频道的使用条款 conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main # 接受 R 语言频道 conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r # 接受 MSYS2 频道(Windows 工具链) conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/msys2 ``` #### 方案2:批量处理脚本 创建 `accept_tos.ps1` 脚本: ```powershell # 所有需要接受 ToS 的频道列表 $channels = @( "https://repo.anaconda.com/pkgs/main", "https://repo.anaconda.com/pkgs/r", "https://repo.anaconda.com/pkgs/msys2" ) foreach ($channel in $channels) { Write-Host "正在接受: $channel" -ForegroundColor Yellow try { conda tos accept --override-channels --channel $channel Write-Host "✅ 成功接受: $channel" -ForegroundColor Green } catch { Write-Host "❌ 失败: $channel - $_" -ForegroundColor Red } } Write-Host "`n所有条款接受完成!" -ForegroundColor Cyan ``` 运行脚本: ```powershell .\accept_tos.ps1 ``` #### 方案3:使用配置文件跳过检查 创建 `.condarc` 文件在用户目录下: ```yaml # C:\Users\24307\.condarc tos: accepted_licenses: - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - https://repo.anaconda.com/pkgs/msys2 ``` --- ### 第二步:验证并创建环境 #### 检查 ToS 状态 ```python # check_tos_status.py import subprocess import json def check_tos_status(): """检查当前 ToS 接受状态""" try: result = subprocess.run([ 'conda', 'config', '--show', 'tos' ], capture_output=True, text=True) print("ToS 配置状态:") print(result.stdout) except Exception as e: print(f"检查失败: {e}") def list_accepted_channels(): """列出已接受的频道""" config_result = subprocess.run([ 'conda', 'config', '--show', 'tos' ], capture_output=True, text=True) if 'accepted_licenses' in config_result.stdout: print("✅ 已接受的频道:") for line in config_result.stdout.split('\n'): if 'https://' in line: print(f" {line.strip()}") else: print("❌ 尚未接受任何频道的条款") if __name__ == "__main__": check_tos_status() list_accepted_channels() ``` #### 创建 swim 环境 ```powershell # 现在可以成功创建环境 conda create -n swim python=3.9 -y # 激活环境 conda activate swim # 验证环境 python -c "print('Swim 环境创建成功!')" ``` --- ### 第三步:自动化环境管理脚本 #### 创建项目初始化脚本 `init_project.ps1` ```powershell <# .SYNOPSIS 初始化 Python 项目环境 .DESCRIPTION 自动处理 ToS 接受、环境创建和依赖安装 #> param( [string]$EnvName = "swim", [string]$PythonVersion = "3.9" ) # 定义频道列表 $channels = @( "https://repo.anaconda.com/pkgs/main", "https://repo.anaconda.com/pkgs/r", "https://repo.anaconda.com/pkgs/msys2" ) # 接受所有必要 ToS foreach ($channel in $channels) { if ((conda tos list --json | ConvertFrom-Json).accepted_licenses -notcontains $channel) { Write-Host "接受条款: $channel" -ForegroundColor Yellow conda tos accept --override-channels --channel $channel } else { Write-Host "已接受: $channel" -ForegroundColor Green } } # 检查环境是否存在 $envExists = (conda info --envs | Select-String -Pattern $EnvName).Length -gt 0 if (-not $envExists) { Write-Host "创建 $EnvName 环境..." -ForegroundColor Cyan conda create -n $EnvName python=$PythonVersion -y } # 激活环境 Write-Host "激活 $EnvName 环境..." -ForegroundColor Cyan conda activate $EnvName # 安装常用包 Write-Host "安装基础包..." -ForegroundColor Cyan conda install -n $EnvName numpy pandas matplotlib opencv-python -y Write-Host "项目初始化完成!" -ForegroundColor Green Write-Host "使用方法: conda activate $EnvName" -ForegroundColor Yellow ``` 运行初始化: ```powershell .\init_project.ps1 ``` --- ### 第四步:永久解决方案 #### 配置全局设置 ```powershell # 设置默认行为 conda config --set always_yes true conda config --set changeps1 false # 添加国内镜像源(可选) conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free conda config --set show_channel_urls yes ``` #### 创建环境模板 创建 `environment-template.yml`: ```yaml name: project-env channels: - defaults - conda-forge dependencies: # Python 版本 - python=3.9 # 基础科学计算 - numpy - pandas - scipy # 可视化 - matplotlib - seaborn # 图像处理 - opencv-python # 机器学习 - scikit-learn # 其他工具 - jupyter - pip # pip 包 - pip: - mediapipe - tensorflow - torch ``` 使用模板创建环境: ```powershell conda env create -f environment-template.yml conda activate project-env ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值