增强ToolFile对斜杠的判断与相关行为
This commit is contained in:
@@ -328,6 +328,12 @@ class PlatformIndicator:
|
|||||||
CompanyName : str = "DefaultCompany"
|
CompanyName : str = "DefaultCompany"
|
||||||
ProductName : str = "DefaultProject"
|
ProductName : str = "DefaultProject"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def GetFileSeparator(is_not_this_platform:bool = False) -> str:
|
||||||
|
if PlatformIndicator.IsPlatformWindows and not is_not_this_platform:
|
||||||
|
return "\\"
|
||||||
|
return "/"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def GetApplicationPath() -> str:
|
def GetApplicationPath() -> str:
|
||||||
"""获取应用程序所在目录"""
|
"""获取应用程序所在目录"""
|
||||||
|
@@ -62,7 +62,7 @@ class ToolFile(BaseModel):
|
|||||||
filePath: Union[str, Self],
|
filePath: Union[str, Self],
|
||||||
):
|
):
|
||||||
filePath = os.path.expandvars(str(filePath))
|
filePath = os.path.expandvars(str(filePath))
|
||||||
if filePath[1:].startswith(":/") or filePath[1:].startswith(":\\"):
|
if ":" in filePath:
|
||||||
filePath = os.path.abspath(filePath)
|
filePath = os.path.abspath(filePath)
|
||||||
super().__init__(OriginFullPath=filePath)
|
super().__init__(OriginFullPath=filePath)
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
@@ -76,19 +76,21 @@ class ToolFile(BaseModel):
|
|||||||
|
|
||||||
def __or__(self, other):
|
def __or__(self, other):
|
||||||
if other is None:
|
if other is None:
|
||||||
return ToolFile(self.GetFullPath() if self.IsDir() else f"{self.GetFullPath()}\\")
|
return ToolFile(self.GetFullPath() if self.IsDir() else f"{self.GetFullPath()}{PlatformIndicator.GetFileSeparator()}")
|
||||||
else:
|
else:
|
||||||
# 不使用os.path.join,因为os.path.join存在如下机制
|
# 不使用os.path.join,因为os.path.join存在如下机制
|
||||||
# 当参数路径中存在绝对路径风格时,会忽略前面的参数,例如:
|
# 当参数路径中存在绝对路径风格时,会忽略前面的参数,例如:
|
||||||
# os.path.join("E:/dev", "/analyze/") = "E:/analyze/"
|
# os.path.join("E:/dev", "/analyze/") = "E:/analyze/"
|
||||||
# 而我们需要的是 "E:/dev/analyze"
|
# 而我们需要的是 "E:/dev/analyze"
|
||||||
first = self.GetFullPath().replace('/','\\').strip('\\')
|
separator = PlatformIndicator.GetFileSeparator()
|
||||||
second = str(other).replace('/','\\')
|
separator_not_this_platform = PlatformIndicator.GetFileSeparator(True)
|
||||||
|
first = self.GetFullPath().replace(separator_not_this_platform,separator).strip(separator)
|
||||||
|
second = str(other).replace(separator_not_this_platform,separator)
|
||||||
if first == "./":
|
if first == "./":
|
||||||
return ToolFile(f"{second}")
|
return ToolFile(f"{second}")
|
||||||
elif first == "../":
|
elif first == "../":
|
||||||
first = ToolFile(f"{os.path.abspath(first)}").BackToParentDir()
|
first = ToolFile(f"{os.path.abspath(first)}").BackToParentDir()
|
||||||
return ToolFile(f"{first}\\{second}")
|
return ToolFile(f"{first}{separator}{second}")
|
||||||
def __idiv__(self, other):
|
def __idiv__(self, other):
|
||||||
temp = self.__or__(other)
|
temp = self.__or__(other)
|
||||||
self.OriginFullPath = temp.GetFullPath()
|
self.OriginFullPath = temp.GetFullPath()
|
||||||
@@ -111,15 +113,18 @@ class ToolFile(BaseModel):
|
|||||||
other_path = other.GetFullPath() if isinstance(other, ToolFile) else str(other)
|
other_path = other.GetFullPath() if isinstance(other, ToolFile) else str(other)
|
||||||
self_path = self.OriginFullPath
|
self_path = self.OriginFullPath
|
||||||
|
|
||||||
|
separator = PlatformIndicator.GetFileSeparator()
|
||||||
|
separator_not_this_platform = PlatformIndicator.GetFileSeparator(True)
|
||||||
|
|
||||||
# 如果两个文件都存在,则直接比较路径
|
# 如果两个文件都存在,则直接比较路径
|
||||||
if self.Exists() == True and other.Exists() == True:
|
if self.Exists() == True and other.Exists() == True:
|
||||||
return self_path.strip('\\/') == other_path.strip('\\/')
|
return self_path.strip(separator_not_this_platform) == other_path.strip(separator_not_this_platform)
|
||||||
# 如果一个文件存在另一个不被判定为存在则一定不同
|
# 如果一个文件存在另一个不被判定为存在则一定不同
|
||||||
elif self.Exists() != other.Exists():
|
elif self.Exists() != other.Exists():
|
||||||
return False
|
return False
|
||||||
# 如果两个文件都不存在,则直接比较文件名在视正反斜杠相同的情况下比较路径字符串
|
# 如果两个文件都不存在,则直接比较文件名在视正反斜杠相同的情况下比较路径字符串
|
||||||
else:
|
else:
|
||||||
return self_path.replace('/','\\') == other_path.replace('/','\\')
|
return self_path.replace(separator_not_this_platform,separator) == other_path.replace(separator_not_this_platform,separator)
|
||||||
|
|
||||||
def ToPath(self):
|
def ToPath(self):
|
||||||
return Path(self.OriginFullPath)
|
return Path(self.OriginFullPath)
|
||||||
@@ -169,7 +174,7 @@ class ToolFile(BaseModel):
|
|||||||
if self.Exists() is False:
|
if self.Exists() is False:
|
||||||
raise FileNotFoundError("file not found")
|
raise FileNotFoundError("file not found")
|
||||||
newpath = str(newpath)
|
newpath = str(newpath)
|
||||||
if '\\' in newpath or '/' in newpath:
|
if PlatformIndicator.GetFileSeparator() in newpath or PlatformIndicator.GetFileSeparator(True) in newpath:
|
||||||
newpath = GetBaseFilename(newpath)
|
newpath = GetBaseFilename(newpath)
|
||||||
new_current_path = os.path.join(self.GetDir(), newpath)
|
new_current_path = os.path.join(self.GetDir(), newpath)
|
||||||
os.rename(self.OriginFullPath, new_current_path)
|
os.rename(self.OriginFullPath, new_current_path)
|
||||||
@@ -180,28 +185,28 @@ class ToolFile(BaseModel):
|
|||||||
with open(self.OriginFullPath, 'r', encoding=encoding) as f:
|
with open(self.OriginFullPath, 'r', encoding=encoding) as f:
|
||||||
json_data = json.load(f, **kwargs)
|
json_data = json.load(f, **kwargs)
|
||||||
return json_data
|
return json_data
|
||||||
def LoadAsCsv(self) -> "pandas.DataFrame":
|
def LoadAsCsv(self) -> "pd.DataFrame":
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
ImportingThrow(e, "File", ["pandas"])
|
ImportingThrow(e, "File", ["pandas"])
|
||||||
with open(self.OriginFullPath, 'r') as f:
|
with open(self.OriginFullPath, 'r') as f:
|
||||||
return pd.read_csv(f)
|
return pd.read_csv(f)
|
||||||
def LoadAsXml(self) -> "pandas.DataFrame":
|
def LoadAsXml(self) -> "pd.DataFrame":
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
ImportingThrow(e, "File", ["pandas"])
|
ImportingThrow(e, "File", ["pandas"])
|
||||||
with open(self.OriginFullPath, 'r') as f:
|
with open(self.OriginFullPath, 'r') as f:
|
||||||
return pd.read_xml(f)
|
return pd.read_xml(f)
|
||||||
def LoadAsDataframe(self) -> "pandas.DataFrame":
|
def LoadAsDataframe(self) -> "pd.DataFrame":
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
ImportingThrow(e, "File", ["pandas"])
|
ImportingThrow(e, "File", ["pandas"])
|
||||||
with open(self.OriginFullPath, 'r') as f:
|
with open(self.OriginFullPath, 'r') as f:
|
||||||
return pd.read_csv(f)
|
return pd.read_csv(f)
|
||||||
def LoadAsExcel(self) -> "pandas.DataFrame":
|
def LoadAsExcel(self) -> "pd.DataFrame":
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
@@ -323,7 +328,7 @@ class ToolFile(BaseModel):
|
|||||||
with open(self.OriginFullPath, 'w', encoding='utf-8') as f:
|
with open(self.OriginFullPath, 'w', encoding='utf-8') as f:
|
||||||
json.dump(json_data, f, indent=4)
|
json.dump(json_data, f, indent=4)
|
||||||
return self
|
return self
|
||||||
def SaveAsCsv(self, csv_data:"pandas.DataFrame"):
|
def SaveAsCsv(self, csv_data:"pd.DataFrame"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -332,7 +337,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
csv_data.to_csv(self.OriginFullPath)
|
csv_data.to_csv(self.OriginFullPath)
|
||||||
return self
|
return self
|
||||||
def SaveAsXml(self, xml_data:"pandas.DataFrame"):
|
def SaveAsXml(self, xml_data:"pd.DataFrame"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -341,7 +346,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
xml_data.to_xml(self.OriginFullPath)
|
xml_data.to_xml(self.OriginFullPath)
|
||||||
return self
|
return self
|
||||||
def SaveAsDataframe(self, dataframe_data:"pandas.DataFrame"):
|
def SaveAsDataframe(self, dataframe_data:"pd.DataFrame"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -350,7 +355,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
dataframe_data.to_csv(self.OriginFullPath)
|
dataframe_data.to_csv(self.OriginFullPath)
|
||||||
return self
|
return self
|
||||||
def SaveAsExcel(self, excel_data:"pandas.DataFrame"):
|
def SaveAsExcel(self, excel_data:"pd.DataFrame"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -367,7 +372,7 @@ class ToolFile(BaseModel):
|
|||||||
with open(self.OriginFullPath, 'w') as f:
|
with open(self.OriginFullPath, 'w') as f:
|
||||||
f.writelines(text_data)
|
f.writelines(text_data)
|
||||||
return self
|
return self
|
||||||
def SaveAsAudio(self, audio_data:"pydub.AudioSegment"):
|
def SaveAsAudio(self, audio_data:"AudioSegment"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
from pydub import AudioSegment
|
from pydub import AudioSegment
|
||||||
@@ -376,7 +381,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
audio_data.export(self.OriginFullPath, format=self.get_extension(self.OriginFullPath))
|
audio_data.export(self.OriginFullPath, format=self.get_extension(self.OriginFullPath))
|
||||||
return self
|
return self
|
||||||
def SaveAsImage(self, image_data:"PIL.ImageFile.ImageFile"):
|
def SaveAsImage(self, image_data:"ImageFile.ImageFile"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
from PIL import Image, ImageFile
|
from PIL import Image, ImageFile
|
||||||
@@ -385,7 +390,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
image_data.save(self.OriginFullPath)
|
image_data.save(self.OriginFullPath)
|
||||||
return self
|
return self
|
||||||
def SaveAsDocx(self, docx_data:"docx.document.Document"):
|
def SaveAsDocx(self, docx_data:"DocumentObject"):
|
||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
from docx import Document
|
from docx import Document
|
||||||
@@ -417,7 +422,7 @@ class ToolFile(BaseModel):
|
|||||||
'''
|
'''
|
||||||
if is_without_extension and '.' in self.OriginFullPath:
|
if is_without_extension and '.' in self.OriginFullPath:
|
||||||
return GetBaseFilename(self.OriginFullPath)[:-(len(self.GetExtension())+1)]
|
return GetBaseFilename(self.OriginFullPath)[:-(len(self.GetExtension())+1)]
|
||||||
elif self.OriginFullPath[-1] == '/' or self.OriginFullPath[-1] == '\\':
|
elif self.OriginFullPath[-1] == PlatformIndicator.GetFileSeparator() or self.OriginFullPath[-1] == PlatformIndicator.GetFileSeparator(True):
|
||||||
return GetBaseFilename(self.OriginFullPath[:-1])
|
return GetBaseFilename(self.OriginFullPath[:-1])
|
||||||
else:
|
else:
|
||||||
return GetBaseFilename(self.OriginFullPath)
|
return GetBaseFilename(self.OriginFullPath)
|
||||||
@@ -429,7 +434,7 @@ class ToolFile(BaseModel):
|
|||||||
return os.path.dirname(self.OriginFullPath)
|
return os.path.dirname(self.OriginFullPath)
|
||||||
|
|
||||||
def IsDir(self):
|
def IsDir(self):
|
||||||
if self.OriginFullPath[-1] == '\\' or self.GetFullPath()[-1] == '/':
|
if self.OriginFullPath[-1] == PlatformIndicator.GetFileSeparator() or self.GetFullPath()[-1] == PlatformIndicator.GetFileSeparator(True):
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return os.path.isdir(self.OriginFullPath)
|
return os.path.isdir(self.OriginFullPath)
|
||||||
@@ -778,8 +783,11 @@ class ToolFile(BaseModel):
|
|||||||
ignore_directories: 是否忽略目录事件
|
ignore_directories: 是否忽略目录事件
|
||||||
case_sensitive: 是否区分大小写
|
case_sensitive: 是否区分大小写
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
from watchdog.observers import Observer
|
from watchdog.observers import Observer
|
||||||
from watchdog.events import FileSystemEventHandler
|
from watchdog.events import FileSystemEventHandler
|
||||||
|
except ImportError as e:
|
||||||
|
ImportingThrow(e, "File", ["watchdog"])
|
||||||
if not self.Exists():
|
if not self.Exists():
|
||||||
raise FileNotFoundError(f"File not found: {self.GetFullPath()}")
|
raise FileNotFoundError(f"File not found: {self.GetFullPath()}")
|
||||||
|
|
||||||
|
@@ -3,10 +3,8 @@ import os
|
|||||||
from time import sleep
|
from time import sleep
|
||||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
from Convention.Runtime.Interaction import *
|
from Convention.Runtime.File import *
|
||||||
|
|
||||||
download = Interaction("http://www.liubai.site:4000/d/storage/Convention/Convention-Unity-Demo/TEST/song.mp3?sign=pIIWFqeous--i4H5fNIpqQsS0HeMinSRA_bztq6Czgo=:0")
|
file = ToolFile("[Test]")|"temp"|None
|
||||||
file = download.Download("./[Test]/test.mp3")
|
print(file.MustExistsPath())
|
||||||
sleep(5)
|
|
||||||
file.Remove()
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user