用python实现读取文件夹中的文件内容,并提取每个文件的第16行的前15个字符放入新的文档,字符内容不能重复
时间: 2023-05-20 08:07:44 浏览: 94
可以采用以下的 Python 代码实现:
```python
import os
files_path = "/path/to/folder" # 替换为你的文件夹路径
result_file = "result.txt" # 替换为你想要保存结果的文件名
lines = set() # 使用 set 存储已经提取过的字符,防止重复
with open(result_file, 'w') as result:
for file_name in os.listdir(files_path):
with open(os.path.join(files_path, file_name), 'r') as f:
file_lines = f.readlines()
if len(file_lines) >= 16:
line_content = file_lines[15][:15]
if line_content not in lines:
lines.add(line_content)
result.write(line_content + "\n")
```
这段代码可以遍历指定的文件夹,读取每个文件的第 16 行的前 15 个字符,然后将这些字符保存到一个新的文档中。字符内容不会重复。
相关问题
用python实现读取文件夹中的文件内容,并提取每个文件的第16行的前15个字符放入新的文档
可以使用以下代码实现:
```python
import os
# 定义文件夹路径
folder_path = "your_folder_path"
# 定义新文档路径
new_file_path = "your_new_file_path"
# 遍历文件夹中的文件
for filename in os.listdir(folder_path):
# 判断是否为文件
if os.path.isfile(os.path.join(folder_path, filename)):
# 打开文件
with open(os.path.join(folder_path, filename), "r") as f:
# 读取第16行的前15个字符
content = f.readlines()[15][:15]
# 写入新文档
with open(new_file_path, "a") as new_file:
new_file.write(content + "\n")
```
其中,`folder_path` 为要读取的文件夹路径,`new_file_path` 为新文档的路径。代码会遍历文件夹中的每个文件,读取每个文件的第16行的前15个字符,并将其写入新文档中。
用python实现读取文件夹中的文件内容,并提取每个文件的第16行的前15个字符放入新的文档,文档中字符内容不能重复出现
可以使用下面的python程序实现读取文件夹中的文件内容,并提取每个文件的第16行的前15个字符放入新的文档,文档中字符内容不能重复出现:
```
import os
def extract_chars_from_file(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
if len(lines) >= 16:
return lines[15][:15]
def extract_chars_from_folder(folderpath, outputpath):
used_chars = set()
with open(outputpath, 'w') as output_file:
for filename in os.listdir(folderpath):
if not os.path.isfile(os.path.join(folderpath, filename)):
continue
extracted_chars = extract_chars_from_file(os.path.join(folderpath, filename))
if extracted_chars and extracted_chars not in used_chars:
output_file.write(extracted_chars + '\n')
used_chars.add(extracted_chars)
```
你可以将文件夹路径和输出文件路径作为参数传递给 extract_chars_from_folder 函数。例如:
```
extract_chars_from_folder('/path/to/folder', '/path/to/output.txt')
```
其中 /path/to/folder 是要遍历的文件夹路径,/path/to/output.txt 是要输出的文件路径。
阅读全文
相关推荐











