Linux用python创建一百个文件,然后遍历这100个文件并把内容存到另一个文件里,以上内容的代码
时间: 2024-05-02 12:20:13 浏览: 7
创建100个文件的代码:
```python
import os
# 创建100个文件
for i in range(1, 101):
filename = f"file_{i}.txt"
with open(filename, "w") as f:
f.write(f"This is file number {i}")
```
遍历这100个文件并把内容存到另一个文件里的代码:
```python
# 遍历100个文件并把内容存到另一个文件里
output_file = "output.txt"
with open(output_file, "w") as out_f:
for i in range(1, 101):
filename = f"file_{i}.txt"
with open(filename, "r") as in_f:
content = in_f.read()
out_f.write(content + "\n")
```
上述代码会创建100个名为 `file_1.txt` 到 `file_100.txt` 的文件,然后遍历这100个文件,依次读取每个文件的内容,并把内容写入到名为 `output.txt` 的文件中。每个文件的内容会单独占一行,行与行之间用换行符分隔。