Найти - Пользователи
Полная версия: нубский вопрос про имена файлов.
Начало » Python для новичков » нубский вопрос про имена файлов.
1 2
py.user.next
>>> import os, sys
>>> os.dirname()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dirname'
>>> sys.dirname()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dirname'
>>> dirname()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dirname' is not defined
>>> help(dirname)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dirname' is not defined
>>>
py.user.next
>>> s = "/home/vasya/test/test.txt"
>>> s = func(s, "re_")
>>> s
'/home/vasya/test/re_test.txt'
>>> s = func(s, "re_", 're_')
>>> s
'/home/vasya/test/re_re_test.txt'
>>> s = func(s, "__1__", 'test')
>>> s
'/home/vasya/test/re_re_test__1__.txt'
>>> func("abc", "re_")
'abc'
>>> func("abc", "re_", "a")
'are_bc'
>>>
UsCr
py.user.next
def func(path, prefix=“”, sep='/'):
… return (“%s%s” % (sep, prefix)).join(path.rsplit(sep, 1))
Ну а вдруг мой код живые люди почитать захотят?
Да и потом на мой взгляд это не есть “элегантное” решение.
py.user.next
import os, sys
>>> os.dirname()
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: ‘module’ object has no attribute ‘dirname’
Это что?
os.path.dirname(PATH) , где PATH - некий путь к файлу.
py.user.next
>>> def func(path, prefix, delim='/'):
... if not delim in path:
... return prefix + path
... return path.rsplit(delim, 1)[0] + delim + prefix + path.rsplit(delim, 1)[-1]
...
>>> def func2(path, prefix):
... import os
... return os.path.join(os.path.dirname(path), prefix + os.path.basename(path))
...
>>> def form():
... l = []
... for i in range(1, 10001):
... l.append("/home/guest/file%d.txt" % i)
... return l
...
>>> def f1():
... outcome = []
... l = form()
... for p in l:
... outcome.append(func(p, "prefix_"))
... return outcome
...
>>> def f2():
... outcome = []
... l = form()
... for p in l:
... outcome.append(func2(p, "prefix_"))
... return outcome
...
>>> from timeit import Timer as reg
>>> t1 = reg(f1)
>>> t2 = reg(f2)
>>> t1.repeat(3, 1)
[0.06797289848327637, 0.04929399490356445, 0.05050206184387207]
>>> t2.repeat(3, 1)
[0.15523314476013184, 0.1336510181427002, 0.13914895057678223]
>>>
да, path поуматнее будет, тем более, что он для этого и предназначен
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB