linux python将目录下utc开头的文件名字提取到指定路径文本,并且文本第一行写demo_test,去除与第一行重复的内容
时间: 2024-02-05 17:13:48 浏览: 26
可以使用如下的 Python 代码实现:
```python
import os
# 指定目录路径和输出文件路径
dir_path = "/path/to/dir"
output_file = "/path/to/output.txt"
# 获取目录下所有文件名
file_names = os.listdir(dir_path)
# 提取以 "utc" 开头的文件名
utc_file_names = [f for f in file_names if f.startswith("utc")]
# 将文件名写入输出文件
with open(output_file, "w") as f:
f.write("demo_test\n")
for name in utc_file_names:
f.write(name + "\n")
```
其中,`os.listdir(dir_path)` 函数可以获取指定目录下的所有文件名,`f.startswith("utc")` 可以判断字符串 `f` 是否以 "utc" 开头。最后,通过 `open(output_file, "w")` 打开输出文件,并使用 `write` 函数将文件名写入文件。注意,在写入第一行 "demo_test" 后,需要在每个文件名后面添加一个换行符 "\n",以便每个文件名单独占据一行。