分别编写读写csv文件和TXT文件的代码
时间: 2024-10-09 13:13:07 浏览: 25
在Python中,我们可以使用内置的`csv`模块处理CSV文件,`open()`函数用于打开文本文件(包括TXT)。以下是简单的读写操作示例:
**读取CSV文件:**
```python
import csv
def read_csv(file_name):
with open(file_name, 'r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 调用函数,传入你的CSV文件名
read_csv('example.csv')
```
**写入CSV文件:**
```python
def write_csv(data_list, file_name):
with open(file_name, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data_list)
# 示例数据,data_list是一个二维列表
data = [['Name', 'Age'], ['John', '25'], ['Jane', '30']]
write_csv(data, 'output.csv')
```
**读取TXT文件:**
```python
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
```
**写入TXT文件:**
```python
def write_txt(text, file_name):
with open(file_name, 'w', encoding='utf-8') as file:
file.write(text)
# 写入文本到文件
text = "Hello, this is a sample text."
write_txt(text, 'output.txt')
```
阅读全文