ptyhon 读取目录下 的所有txt 依次合并写入新文件 依次 a.txt 和b.txt 内容 写入new.txt 逻辑为 随机2个tt a[1] b[1] a[2] b[2]
时间: 2023-06-06 14:07:40 浏览: 49
好的,这个问题属于技术问题,我可以为您提供代码示例。以下是符合您需求的Python代码:
```
import os
import random
# 获取目录下所有txt文件
files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.txt')]
# 读取每个txt文件的内容
texts = []
for f in files:
with open(f, 'r') as file:
texts.append(file.read())
# 将内容随机组合
random.shuffle(texts)
combined_text = ''
for i in range(0, len(texts), 2):
combined_text += texts[i] + texts[i+1]
# 将组合后的内容写入new.txt文件
with open('new.txt', 'w') as file:
file.write(combined_text)
```
代码中,首先获取目录下所有txt文件的路径。然后按顺序读取每个文件的内容,存入一个列表中。接着对这个列表进行随机打乱顺序,将相邻两个元素拼接起来形成一个新的字符串。最后将这个字符串写入new.txt文件。运行上述代码后,new.txt文件中将会包含a.txt和b.txt两个文件内容的随机组合。
相关问题
python 读取目录下所有txt 获取每个txt 同一行 写入新的txt
可以使用os模块中的listdir函数获取目录下的所有文件名,再利用open函数逐个读取每个txt文件,将同一行的文本写入新的txt文件中。
以下是Python代码示例:
```
import os
# 定义目录路径
path = "目录路径"
# 列出目录下所有文件名
file_list = os.listdir(path)
# 打开新的txt文件,准备写入内容
with open("new_file.txt", "w") as f:
for filename in file_list:
# 判断文件是否为txt文件
if filename.endswith(".txt"):
# 读取txt文件
with open(os.path.join(path, filename), "r") as old_file:
# 逐行读取文本
for line in old_file:
# 写入同一行的文本到新的txt文件中
f.write(line.strip() + " ")
# 写入一个制表符,便于区分不同的txt文件
f.write("\t")
```
以上代码会将目录下所有txt文件的同一行文本写入到新的txt文件中,每个txt文件占据一行,不同的txt文件之间用制表符隔开。
使用Python.自定义文件a.txt,编程读取该文件,并将其写入b.txt中。
好的,下面是代码:
```python
# 打开文件a.txt,并读取其中的内容
with open('a.txt', 'r') as f:
content = f.read()
# 将读取的内容写入文件b.txt
with open('b.txt', 'w') as f:
f.write(content)
```
在这里,我们使用了 Python 的文件操作来读取文件 `a.txt` 中的内容,并将其写入到文件 `b.txt` 中。首先,我们使用 `open` 函数打开文件 `a.txt`,并指定文件模式为读取模式 `'r'`,然后使用 `read` 方法读取文件的全部内容,并将其存储在变量 `content` 中。接下来,我们再次使用 `open` 函数打开文件 `b.txt`,并指定文件模式为写入模式 `'w'`,然后使用 `write` 方法将变量 `content` 的内容写入到文件 `b.txt` 中。最后,我们使用 `with` 语句来自动关闭文件,避免出现未关闭文件的问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)