读取指定文件夹内的所有txt文件到同意列表,且列表每一行包含一个txt文档
时间: 2024-05-14 15:19:31 浏览: 16
好的,这个问题需要通过编程实现,您需要先指定一个文件夹路径。然后使用Python的os模块来获取该文件夹内的所有文件名,筛选出txt文件,并将文件名存储到一个列表中。最后将列表中的文件名依次连接起来,存储到一个新的txt文档中。以下是Python代码示例:
```python
import os
# 指定文件夹路径
folder_path = "/path/to/folder"
# 获取文件夹内的所有文件名
files = os.listdir(folder_path)
# 筛选出txt文件
txt_files = [f for f in files if f.endswith(".txt")]
# 存储文件名到列表中
file_names = []
for txt_file in txt_files:
file_names.append(txt_file + "\n")
# 连接文件名并存储到新的txt文档中
with open("all_files.txt", "w") as f:
f.writelines(file_names)
```
执行该代码后,您将得到一个名为“all_files.txt”的文件,其中包含指定文件夹内所有txt文件的文件名,每行一个文件名。
相关问题
遍历txt文件夹,提取前15个关键词,以每个文件为一行输出到新的txt文档中
好的,可以使用Python编写脚本来实现。您需要先安装Python和相关的库,如nltk和os。以下是可能的实现方式:
```python
import os
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.probability import FreqDist
# 设置文件夹路径和输出文件名
folder_path = "path/to/folder"
output_file = "output.txt"
# 获取停用词列表
stop_words = set(stopwords.words("english"))
# 遍历文件夹
with open(output_file, "w") as f:
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
# 打开文件并读取内容
with open(file_path, "r") as file:
content = file.read()
# 分词
tokens = word_tokenize(content)
# 去除停用词和标点符号
words = [word.lower() for word in tokens if word.isalpha() and word.lower() not in stop_words]
# 计算词频并获取前15个关键词
freq_dist = FreqDist(words)
keywords = [word[0] for word in freq_dist.most_common(15)]
# 将关键词写入输出文件
f.write(" ".join(keywords) + "\n")
```
请将`path/to/folder`替换为您的文件夹路径,将`output.txt`替换为您想要的输出文件名。该脚本将遍历文件夹中的每个文件,提取前15个关键词,并将这些关键词作为一行写入输出文件中。
遍历文件夹中的文件,给每个文档第一行的末尾加一个;
以下是Python代码实现:
```python
import os
folder_path = "path/to/folder" # 文件夹路径
for filename in os.listdir(folder_path): # 遍历文件夹中的文件
if filename.endswith(".txt"): # 如果是txt文件
file_path = os.path.join(folder_path, filename) # 获取文件路径
with open(file_path, "r+") as file: # 以读写模式打开文件
first_line = file.readline() # 获取第一行的内容
if not first_line.endswith(";"): # 如果末尾没有分号
file.seek(0) # 将光标移到文件开头
file.write(first_line.rstrip() + ";") # 在末尾加上分号
file.write("\n") # 写入换行符
```
代码解析:
1. 首先定义文件夹路径 `folder_path`。
2. 使用 `os.listdir()` 函数遍历文件夹中的文件,获取文件名 `filename`。
3. 判断文件是否为txt文件,可以使用 `filename.endswith(".txt")` 来判断。
4. 如果是txt文件,使用 `os.path.join()` 函数获取文件路径 `file_path`。
5. 使用 `with open(file_path, "r+") as file` 打开文件,以读写模式打开文件,这样可以同时读取和修改文件。
6. 使用 `file.readline()` 函数获取第一行的内容 `first_line`。
7. 判断第一行的末尾是否已经有分号,如果没有分号,使用 `file.seek(0)` 函数将光标移到文件开头,使用 `file.write()` 函数在第一行末尾加上分号,并在行末写入换行符。
8. 由于使用了 `with` 上下文管理器,所以文件会自动关闭。