1. 打开一个英文文本文件(test.txt;里面内容为I love python),编写程序读取其内容,并把其中的大写字母变成小写字母,小写字母变成大写字母.
时间: 2024-03-08 18:47:29 浏览: 19
好的,以下是 Python 代码实现:
```python
with open('test.txt', 'r') as f:
text = f.read()
converted_text = ''
for char in text:
if char.islower():
converted_text += char.upper()
elif char.isupper():
converted_text += char.lower()
else:
converted_text += char
print(converted_text)
```
这段代码首先打开 `test.txt` 文件并读取其中的内容,然后遍历每个字符,如果是小写字母就转换成大写字母,反之亦然。最后将转换后的文本输出到控制台。
相关问题
python编写程序,创建一个文本文件test.txt,并向其中写入字符串hello world
好的,以下是Python代码实现:
```
with open("test.txt", "w") as file:
file.write("hello world")
```
这段代码会在当前运行的目录下创建一个名为test.txt的文本文件,并将字符串"hello world"写入该文件中。
python中打开指定路径d:盘下创建test.txt文本文件,读取并输出其内容。
你可以使用以下代码在 Python 中打开指定路径 D 盘下创建 test.txt 文本文件,并读取并输出其内容:
```python
# 打开文件并写入内容
with open("D:/test.txt", "w") as f:
f.write("Hello, World!")
# 读取文件内容并输出
with open("D:/test.txt", "r") as f:
content = f.read()
print(content)
```
这段代码首先使用 `with open("D:/test.txt", "w") as f` 打开文件并以写入模式写入内容,接着使用 `with open("D:/test.txt", "r") as f` 打开文件并以读取模式读取内容,最后使用 `print(content)` 输出文件内容。