打开文件“古诗.txt”,逐行读出内容并显示在屏幕上。要求文件名通过input函数输入。
时间: 2023-12-10 22:39:19 浏览: 24
好的,以下是Python代码实现:
```python
filename = input("请输入文件名:") # 获取文件名
try:
with open(filename, 'r', encoding='utf-8') as f: # 打开文件
for line in f: # 逐行读取文件内容
print(line.strip()) # 去除行末换行符并打印
except FileNotFoundError:
print("文件不存在!")
```
其中,`input()`函数用于获取用户输入的文件名,`open()`函数用于打开文件。由于文件中可能存在中文字符,因此通过指定`encoding='utf-8'`参数来指定文件编码格式。使用`with`语句可以自动关闭文件。`for`循环逐行读取文件内容,`strip()`方法用于去除行末的换行符`\n`,`print()`函数将内容输出到屏幕上。如果文件不存在,则会抛出`FileNotFoundError`异常,我们通过`try...except`语句来捕获并处理该异常。
相关问题
打开文件“古诗.txt”,逐行读出内容并显示在屏幕上。要求文件名通过input函数输入。
好的,以下是代码实现:
```python
filename = input("请输入文件名:")
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
```
这段代码中,我们首先通过 input 函数获取了用户输入的文件名,然后使用 `with open()` 语句打开文件,指定了文件名、打开模式(只读模式 `'r'`)和编码方式(UTF-8)。接着,我们使用 for 循环逐行读取文件内容,并通过 `print()` 函数显示在屏幕上,`line.strip()` 方法可以去除每行末尾的换行符。最后,当 with 语句块执行完毕时,Python 会自动关闭文件,无需手动调用 `f.close()` 方法。
python打开文件“古诗.txt”,逐行读出内容并显示在屏幕上。要求文件名通过input函数输入。
可以使用以下代码实现:
```python
filename = input("请输入文件名:")
with open(filename, "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
```
其中,`input()` 函数用于获取用户输入的文件名,`open()` 函数用于打开文件并返回文件对象,`for` 循环逐行读取文件内容并使用 `print()` 函数显示在屏幕上。需要注意的是,文件名需要包含文件后缀名,并且需要指定文件编码为 UTF-8,以避免中文乱码。`with` 语句用于自动关闭文件,可以保证程序的健壮性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)