py代码实现 6. 将字符串”Hello World!\n123\n”写入文件test.txt; 按多行读取文件test.txt。
时间: 2024-05-02 20:22:54 浏览: 18
好的,这个问题很简单。以下是 Python 代码实现:
```python
# 将字符串写入文件
with open('test.txt', 'w') as f:
f.write('Hello World!\n123\n')
# 按多行读取文件
with open('test.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
```
代码的第一部分将字符串写入文件 `test.txt`,使用 `with open()` 语句打开文件并使用 `'w'` 模式写入字符串,`\n` 用于换行。
代码的第二部分按多行读取文件 `test.txt`,同样使用 `with open()` 语句打开文件并使用 `'r'` 模式读取文件内容。使用 `readlines()` 方法读取文件并将每一行存储在列表 `lines` 中,然后使用 `for` 循环遍历每一行并打印出来,使用 `strip()` 方法删除每行末尾的换行符。
相关问题
python 读取test.py 文件将 里面的指定字符串的替换后保存
可以使用 Python 的文件操作和字符串操作实现这个需求。具体步骤如下:
1. 打开文件,读取文件内容。
```python
with open('test.py', 'r') as f:
content = f.read()
```
2. 使用字符串的 replace 方法替换指定字符串。
```python
old_str = 'old string'
new_str = 'new string'
content = content.replace(old_str, new_str)
```
3. 将修改后的内容写入文件。
```python
with open('test.py', 'w') as f:
f.write(content)
```
完整代码如下:
```python
with open('test.py', 'r') as f:
content = f.read()
old_str = 'old string'
new_str = 'new string'
content = content.replace(old_str, new_str)
with open('test.py', 'w') as f:
f.write(content)
```
请注意,在替换字符串时需要确保指定的字符串在文件中确实存在,否则替换操作将不会生效。
读取student.txt中的内容,将其按相反的顺序写入另一个文本文件。
好的,我可以为您实现将文件内容按相反顺序写入另一个文件的操作。以下是示例代码:
```python
with open("student.txt", "r") as f1:
lines = f1.readlines()
with open("student_reverse.txt", "w") as f2:
f2.writelines(reversed(lines))
```
以上代码中,我们首先使用with语句打开一个名为"student.txt"的文本文件,并以只读模式("r")打开。使用readlines()方法读取整个文件内容,并将每一行作为一个字符串保存到一个列表中。
接着,我们再使用with语句打开一个名为"student_reverse.txt"的文本文件,并以写入模式("w")打开。使用writelines()方法将列表中的字符串按相反顺序写入到另一个文件中,即完成了将文件内容按相反顺序写入另一个文件的操作。
注意:以上代码中,我们假设文件中每一行都以换行符"\n"结尾。如果文件中的行末没有换行符,该代码会将多行字符串拼接成一行写入另一个文件中。如果您需要保留每行字符串的原始格式,请确保文件中每一行都以换行符"\n"结尾。
您可以将以上代码保存到一个.py文件中,运行后会自动将"student.txt"文件中的内容按相反顺序写入到"student_reverse.txt"中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)