今天分享一下实习过程减轻工作中一些下载使用后无用的文件的快速删除的代码!
先上代码吧!哈哈!
import os
import glob
# Define a function to delete text files, handling null bytes in paths
def delete_csv_files(directory):
# Ensure the directory name is valid and doesn't contain null bytes
clean_directory = directory.replace('\0', '')
# Use os.listdir to get all files in the directory
files = os.listdir(clean_directory)
# Iterate over found files and check for .csv files
csv_files = []
for file in files:
if '\0' in file:
file = file.replace('\0', '')
if file.endswith('.csv'):
csv_files.append(os.path.join(clean_directory, file))
# Iterate over found .csv files and remove them
for csv_file in csv_files:
try:
os.remove(csv_file)
print(f"Deleted {csv_file}")
except OSError as e:
print(f"Error deleting {csv_file}: {e}")
# Assuming the directory is provided here as an example
directory = r"D:\xxx"
# Call the function with the directory
delete_csv_files(directory)
print("执行完成")
文件类型我们可以更改不一定是csv文件,还可以是txt等等不同类型的文件
只需要修改这个:
if file.endswith('.csv'):
如果是txt就修改为将.csv => .txt即可!
感谢各位的观看,创作不易,能不能给哥们来一个点赞呢!!!
好了,今天的分享就这么多了,有什么不清楚或者我写错的地方,请多多指教!
私信,评论我呗!!!!!!
关注我下一篇不迷路哦!