从键盘输入一首唐诗,把它写到指定的文件(poem.txt)。 示例1: 请输入文件名: poem.txt 请输入一首唐诗,写入该文件,并读出文件显示。
时间: 2024-03-05 09:51:23 浏览: 33
好的,以下是 Python 代码实现:
```python
# 从键盘输入文件名和唐诗
filename = input("请输入文件名:")
poem = input("请输入一首唐诗:")
# 将唐诗写入指定文件
with open(filename, "w", encoding="utf-8") as f:
f.write(poem)
# 读取文件并显示内容
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
print(content)
```
使用方法:
1. 运行上述 Python 代码
2. 根据提示输入文件名和唐诗
3. 程序会将唐诗写入指定文件,并读取文件内容显示出来
相关问题
编写一个JAVA程序先将键盘输入的一首诗词存入文件poem.txt,然后再从文件poem.txt内读出后加上行号打印在屏幕上
好的,我来为您编写这个程序。
```java
import java.io.*;
public class Poem {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String poem = null;
try {
System.out.println("请输入诗词:");
poem = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
File file = new File("poem.txt");
try {
FileWriter fw = new FileWriter(file);
fw.write(poem);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null) {
System.out.println(lineNumber++ + " " + line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序会先让用户从键盘输入一首诗词,然后将它存入 `poem.txt` 文件中,接着再从文件中读出内容并加上行号打印在屏幕上。
python4. 把一首唐诗写入文本文件poem.txt中。唐诗如下:从军行唐.王昌龄青海长云暗雪山,孤城遥望玉门关。黄沙百战穿金甲,不破楼兰终不还。
好的,以下是将唐诗写入文本文件"poem.txt"的示例代码:
```python
poem = "从军行唐.王昌龄\n青海长云暗雪山,孤城遥望玉门关。\n黄沙百战穿金甲,不破楼兰终不还。"
with open("poem.txt", "w") as f:
f.write(poem)
```
首先,我们将唐诗存储在名为poem的字符串变量中。接下来,我们使用with open语句打开"poem.txt"文件并将其存储在变量f中。我们使用内置的write函数将唐诗写入文件中,最后使用with语句退出文件并保存。
你可以将示例代码中的唐诗替换为你自己的文本,并将文件名替换为你自己的文件名。运行代码后,唐诗将被写入指定的文件中。