python编码笔试题

目录

1.打开指定文件,显示文件内容

2.打开文件夹下所有txt文件,并且打开子文件夹,找出所有txt文件。打印出文件名,和文件内容


C:\\Users\\Desktop\\a.txt的内容

bash 复制代码
First line.
Second line.
Third line.

1.打开指定文件,显示文件内容

在 Python 中,使用 with open 语句打开文件时,文件会在代码块执行完毕后自动关闭,无需显式调用 close() 方法。这种模式称为上下文管理器(context manager),它确保资源(如文件)在使用后被正确释放。

语法

python 复制代码
with open('filename.txt', 'r') as file:
    # 文件操作代码
    content = file.read()
# 文件在此处自动关闭

替代方案‌:若需手动控制关闭,可使用 try-finally:

python 复制代码
file = open('filename.txt', 'r')
try:
    content = file.read()
finally:
    file.close()  # 手动关闭
python 复制代码
fname="C:\\Users\\Desktop\\a.txt"
"""1. 使用open函数读取文件
在Python中,读取文件最基本的方式是使用内置的open函数。第1个参数是文件地址,第2个参数是读取模式,第3个参数是编码。这个函数返回一个文件对象,你可以用它来读取文件内容 .with语句确保文件在读取完毕后自动关闭。file.read():读取文件全部内容
"""
print("=======open")
with open(fname,'r',encoding='utf-8') as file:
 content=file.read()
 print(content)

"""
对于大文件,一次性读取全部内容可能会消耗大量内存。按行读取是一个更好的选择。strip()去除每行末尾的换行符
"""
print("=======open\n line")
with open(fname,'r',encoding='utf-8') as file:
 for line in file:
  print(line.strip())

"""
写入文件同样使用open函数,但模式要改为'w'(写入)或'a'(追加)
"""
print("=======w,a")
# 写入文件  
with open(fname, 'w', encoding='utf-8') as file:  
    file.write('Hello, Python!\n')  
    file.write('Welcome to file operations.')  
 
# 追加内容到文件  
with open(fname, 'a', encoding='utf-8') as file:  
    file.write('\nGoodbye, Python!') 
"""
你可以使用writelines方法一次性写入多行内容。
"""
print("=======writelines")
lines_to_write = ['First line.\n', 'Second line.\n', 'Third line.\n']  
with open(fname, 'w', encoding='utf-8') as file:  
    file.writelines(lines_to_write) 
"""
readlines方法会读取文件所有行,并返回一个包含每行内容的列表
"""
print("=======readlines")
with open(fname, 'r', encoding='utf-8') as file:  
    lines = file.readlines()  
    for line in lines:  
        print(line.strip()) 

运行结果

bash 复制代码
=======open
First line.
Second line.
Third line.

=======open
 line
First line.
Second line.
Third line.
=======w,a
=======writelines
=======readlines
First line.
Second line.
Third line.

2.打开文件夹下所有txt文件,并且打开子文件夹,找出所有txt文件。打印出文件名,和文件内容

在Python中,使用os.listdir函数可以列出目录中的文件和子目录。如果你想要递归地打开一个目录及其所有子目录,可以使用os.walk函数,它提供了一个更高级的方式来遍历目录树。

下面os.listdir使用的语法

python 复制代码
import os
 
# 打开文件
COOKED_FOLDER = 'C:\\Users\\Desktop\\'  #文件夹的地址
dirs = os.listdir( COOKED_FOLDER )
 
# 输出所有文件和文件夹
for file in dirs:
   #print(file)  #输出所有文件夹名字
   filepath = COOKED_FOLDER + file  #文件所在地址
   lname=file.split(".")[-1] if "." in file else "" #如果没有if else,文件名没有后缀的时候,lname就是文件名
   #print(lname)
   if lname=='txt': 
    print(filepath)
    with open(filepath,'r') as f:   #读取文件
      for line in f :  #          #按行遍历文件内容
         print(line)  #输出每行信息

打开了桌面文件夹,发现下面只有一个txt文件。输出结果

bash 复制代码
C:\Users\Desktop\a.txt
First line.

Second line.

Third line.

下面是使用os.walk的语法

python 复制代码
import os 
# 打开文件
fname = 'C:\\Users\\99757\\Desktop\\exa'  #文件夹的地址
#定义函数
def readd(top_dir):
  for root,dirs,files in os.walk(top_dir):
    for file in files:
       if (file.endswith('.txt')):
          print(f'文件:{root},{file}')

readd(fname)#调用函数

在这个示例中,os.walk(top_dir)会生成一个三元组(root, dirs, files),其中:

root是当前正在遍历的目录路径。

dirs是一个包含root下所有子目录名的列表。

files是一个包含root下所有非目录文件名的列表。

通过这种方式,你可以递归地访问和打印出所有子目录和文件。如果你想对每个子目录进行进一步的操作,你可以在循环遍历dirs时添加你的代码。

相关推荐
SelectDB3 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码11 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab