利用python编写程序,将字符串“Hello Python”、“BigDate”、“SQL”存入到文件“data.dat”中 并读出显示。
时间: 2023-11-05 19:01:43 浏览: 124
写入文件的代码如下:
```python
data = ["Hello Python", "BigDate", "SQL"]
with open("data.dat", "w") as f:
for item in data:
f.write("%s\n" % item)
```
读取文件并显示的代码如下:
```python
with open("data.dat", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
```
运行以上两段代码后,控制台会输出以下结果:
```
Hello Python
BigDate
SQL
```
相关问题
用python编写程序,将字符串“Hello Python”、“BigDate”、“SQL”存入到文件“data.dat”中并读出显示。
: orders) {
System.out.println(order.toString());
}
}
// 订单类
static class Order {
private Map好的,以下是 Python 代码实现:
```python
# 写入数据到文件
with open("data.dat", "w<String, Integer> dishes = new HashMap<>();
private double totalPrice = 0.0;
public void addDish(String dish,") as file:
file.write("Hello Python\n")
file.write("BigData\n")
file.write("SQL\n")
# int quantity) {
dishes.put(dish, quantity);
totalPrice += menu.get(dish) * quantity;
}
public double getTotalPrice() {
return totalPrice;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("订单读取文件中的数据并显示
with open("data.dat", "r") as file:
data = file.read()
print(data)
```
运行结果:
```
Hello Python
BigData
SQL
```
编写程序,将字符串“Hello Python”、“BigDate”、“SQL”存入到文件“data.dat”中并读出显示
好的,下面是 Python 的代码实现:
```python
# 写入文件
with open('data.dat', 'w') as f:
f.write('Hello Python\n')
f.write('BigData\n')
f.write('SQL\n')
# 读取文件
with open('data.dat', 'r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
```
运行后输出结果为:
```
Hello Python
BigData
SQL
```
其中,`with open('data.dat', 'w') as f:` 打开文件并以写入模式写入数据,`f.write()` 写入数据,`with open('data.dat', 'r') as f:` 打开文件并以读取模式读取数据,`f.readlines()` 读取所有行,`for line in lines:` 循环遍历每一行数据并输出。
阅读全文