我将文件夹内容(包含.pdf .doc和.xls的文件)写入一个小的txt文件。每个文件名都会在txt文件中换行。工作良好。 现在,我想删除所有与.pdf文件的行。 我仍然使用以下代码删除错误的条目(在这种情况下为ail.png):
def clean():
with open("files.txt", "r") as f:
lines = f.readlines()
with open("files.txt", "w") as f:
for line in lines:
if line.strip("\n") != "fail.png":
f.write(line)
clean_folderlog()
是否可以使用某种“通配符”(* .pdf)代替特定的文件名? 还是有其他完整的解决方案?
非常感谢
答案 0 :(得分:0)
有多个选项:
您可以检查行中是否包含字符串“ .pdf”:
if not "pdf" in line.strip("\n")
f.write(line)
您也可以使用regular expression。这在您想要更复杂的模式匹配的其他情况下很有用。
import re
with open("testdata.txt", "w") as f:
for line in lines:
line = line.strip()
if not re.match(".+\.pdf$",line):
f.write(line)
.+
匹配任何字符\.
与文字点匹配pdf
与文字字符'pdf'匹配$
在行尾匹配整个代码如下:
def clean():
with open("files.txt", "r") as f:
lines = f.readlines()
with open("files.txt", "w") as f:
for line in lines:
if not "pdf" in line.strip("\n"):
f.write(line)
clean_folderlog()
我还修复了缩进,因为不必对写开放进行缩进
答案 1 :(得分:0)
您有很多选择:
检查字符串是否以“ .pdf”结尾:
if not line.endswith(".pdf"):
使用re
模块(最常规的模式匹配):
import re
...
if not re.match(r"\.pdf$", line):
使用fnmatch
模块进行外壳样式的模式匹配:
from fnmatch import fnmatch
....
if not fnmatch(line, "*.pdf"):
答案 2 :(得分:0)
您可以轻松地替换写文件夹内容和删除不需要的文件这两个功能,例如,如下所示的代码段:
import os
extensions = ['.pdf', 'PUT_YOUR_OTHER_EXTENSIONS']
with open('test.txt', 'w') as f:
for file_name in os.listdir('PUT_YOUR_FOLDER_PATH'):
if os.path.isfile(file_name) and not file_name.endswith(tuple(extensions)):
f.write("%s\n" % file_name)
它将在文件中写入文件夹的所有文件名。您只需要放入不需要的列表扩展名。享受吧!
注意:此功能适用于os.listdir()
函数中提到的一个文件夹。要从子文件夹写入所有文件,请使用递归遍历。