python如何读多个文件
时间: 2024-02-02 14:03:16 浏览: 26
你可以使用 Python 的 glob 模块来读取多个文件,示例代码如下:
```python
import glob
# 获取路径下所有以 .txt 结尾的文件
files = glob.glob('/path/to/files/*.txt')
# 依次读取每个文件
for file in files:
with open(file, 'r') as f:
content = f.read()
print(content)
```
注意,上述代码仅仅是一个示例,具体代码还要根据你的实际情况进行修改。
相关问题
Python 读大型csv 文件
在Python中,我们可以使用pandas库来读取大型csv文件。pandas库是一个开源数据分析工具包,可以用于处理和分析大型数据集。
以下是读取大型csv文件的步骤:
1. 导入pandas库
```python
import pandas as pd
```
2. 使用pandas的read_csv()函数读取csv文件
```python
df = pd.read_csv('filename.csv', iterator=True, chunksize=1000)
```
其中,'filename.csv'是你要读取的文件名,iterator=True表示返回一个迭代器对象,chunksize=1000表示每次读取1000行数据。
3. 遍历迭代器对象并处理数据
```python
for chunk in df:
# 处理数据
```
遍历迭代器对象可以逐块读取数据,从而避免内存不足的问题。在for循环中,每个chunk都是一个DataFrame对象,你可以对其进行任何数据处理操作。
4. 合并数据
如果你需要将所有数据合并为一个DataFrame对象,可以使用pandas的concat()函数:
```python
df = pd.concat([chunk for chunk in df])
```
这将把所有块合并为一个DataFrame对象。
注意:当读取大型csv文件时,可能需要花费一些时间。因此,你可能需要考虑使用多线程或分布式计算框架来加速处理过程。
python 读文件属性
你可以使用 Python 的 os 模块来读取文件属性。以下是一些常见的文件属性及其对应的 Python 函数:
1. 文件大小:使用 os.path.getsize(file_path) 函数来获取文件大小,返回值为字节数。
2. 创建时间和最后修改时间:使用 os.path.getctime(file_path) 函数来获取文件创建时间,返回值为时间戳;使用 os.path.getmtime(file_path) 函数来获取文件最后修改时间,返回值也为时间戳。
3. 文件权限和所有者:使用 os.stat(file_path) 函数获取文件的所有属性信息,返回值为一个元组,其中包含了很多属性信息,例如 st_mode 表示文件的权限信息,st_uid 表示文件所有者的用户 ID。
下面是一个示例代码,演示如何获取文件的大小、创建时间和最后修改时间:
```python
import os
file_path = 'test.txt'
# 获取文件大小
file_size = os.path.getsize(file_path)
print(f'文件大小:{file_size} 字节')
# 获取文件创建时间
create_time = os.path.getctime(file_path)
print(f'创建时间:{create_time}')
# 获取文件最后修改时间
modify_time = os.path.getmtime(file_path)
print(f'最后修改时间:{modify_time}')
```
注意,以上代码只能在 Unix/Linux 系统上运行,如果你在 Windows 上运行,可能会出现错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)