如何删除 os.walk 显示的名称的一部分?
How do I remove a part of a name that os.walk shows?
所以我有很多目录,不想逐一单击以查看其中有哪些文件。所以我做了一个简短的脚本,这对我来说更容易。我遇到的唯一问题是有些文件名超长。有没有办法可以缩短名称的输出?这是代码
path = 'G:/'
for root, dirs, files in os.walk(path):
for name in files:
print(os.path.join(root, name, '\n')
我可以删除输出的最后 10 个字母吗?
顺便说一句,如果我做错了,这是我第一次在这里发帖...
如果您只想在超长时对输出进行切片:
maxLen = 85
for name in files:
pathname = os.path.join(root, name, '\n')
if len(pathname) > maxLen:
#Trims the string only if it's longer than maxLen
pathname = pathname[:maxLen]+"..." #Trailing dots indicate that has been trimmed
print(pathname)
或者,按照 @Cory Kramer 的建议,您可以 trim 字符串:
print(os.path.join(root, name, '\n')[:-10]) #Removes the last 10 characters in every case
所以我有很多目录,不想逐一单击以查看其中有哪些文件。所以我做了一个简短的脚本,这对我来说更容易。我遇到的唯一问题是有些文件名超长。有没有办法可以缩短名称的输出?这是代码
path = 'G:/'
for root, dirs, files in os.walk(path):
for name in files:
print(os.path.join(root, name, '\n')
我可以删除输出的最后 10 个字母吗?
顺便说一句,如果我做错了,这是我第一次在这里发帖...
如果您只想在超长时对输出进行切片:
maxLen = 85
for name in files:
pathname = os.path.join(root, name, '\n')
if len(pathname) > maxLen:
#Trims the string only if it's longer than maxLen
pathname = pathname[:maxLen]+"..." #Trailing dots indicate that has been trimmed
print(pathname)
或者,按照 @Cory Kramer 的建议,您可以 trim 字符串:
print(os.path.join(root, name, '\n')[:-10]) #Removes the last 10 characters in every case