用Python编写的隐藏文件的小工具
发布时间:2023-12-19 00:44:51
以下是一个使用Python编写的隐藏文件的小工具的示例代码:
import os
def hide_file(file_path):
try:
# 将文件名前面添加一个点,使其成为隐藏文件
new_file_path = os.path.join(os.path.dirname(file_path), "." + os.path.basename(file_path))
# 重命名文件
os.rename(file_path, new_file_path)
return True
except:
return False
def unhide_file(file_path):
try:
# 将文件名前面的点去掉,恢复为正常文件
new_file_path = os.path.join(os.path.dirname(file_path), os.path.basename(file_path)[1:])
# 重命名文件
os.rename(file_path, new_file_path)
return True
except:
return False
# 使用示例
file_path = "/path/to/your/file.txt"
# 隐藏文件
if hide_file(file_path):
print("文件已隐藏")
else:
print("无法隐藏文件")
# 恢复文件
if unhide_file(file_path):
print("文件已恢复")
else:
print("无法恢复文件")
使用上述代码,你只需要将文件的路径替换到file_path变量中,就可以隐藏或恢复文件了。
注意:该工具仅在Unix(包括Linux和Mac OS)系统中有效,Windows系统无法通过给文件名添加点来隐藏文件。
