写一个python读取和写入数据例子
时间: 2023-03-14 10:03:53 浏览: 88
示例代码:# 导入 CSV 模块
import csv
# 将数据写入 CSV 文件
with open('data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['name', 'age'])
writer.writerow(['Bob', '19'])
writer.writerow(['Tom', '20'])
# 从 CSV 文件读取数据
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
相关问题
python读取和写入txt文件
Python提供了许多方法来读写文本文件。其中最常用的方法是使用open()函数打开文件,然后使用read()或write()方法读取或写入文件内容。
以下是一个简单的例子,演示了如何读取和写入文本文件:
读取文件:
```python
with open('filename.txt', 'r') as file:
data = file.read()
print(data)
```
这里我们使用了Python的with语句来打开文件,这样就不需要手动关闭文件了。read()方法将整个文件读入一个字符串中,并打印出来。
写入文件:
```python
with open('filename.txt', 'w') as file:
file.write('Hello World!')
```
这里我们使用了Python的with语句来打开文件,并指定了文件模式为写入模式。然后我们使用write()方法将字符串写入文件中。
python 读取文件 写入字典
在Python中,你可以使用内置的`open()`函数和文件操作来读取文件内容并将其转换为字典。这里是一个基本的例子:
```python
# 打开文件,如果不存在则创建(默认模式是'r', 可以选择其他如'a'追加)
with open('file.txt', 'r') as file:
# 读取文件的每一行,假设每行数据是以逗号分隔的键值对
lines = file.read().splitlines()
# 创建空字典
data_dict = {}
# 遍历每一行,将每一对分割的值作为键值添加到字典中
for line in lines:
key, value = line.split(',')
data_dict[key] = value
# 现在data_dict包含了从文件中读取的内容
print(data_dict)
# 如果需要写入字典回文件,可以这样做:
with open('file.txt', 'w') as file:
for key, value in data_dict.items():
file.write(f'{key},{value}\n')
```
在这个例子中,我们假设文件内容是文本格式,每行有一个键值对,通过`read()`获取所有行,然后逐行处理。写入文件时,同样遍历字典,每个键值对写成一行。
阅读全文
相关推荐
















