相关疑难解决方法(0)

os.path.dirname(__ file__)返回空

我想获取当前目录的路径,在该目录下执行.py文件.

例如,一个D:\test.py包含代码的简单文件:

import os

print os.getcwd()
print os.path.basename(__file__)
print os.path.abspath(__file__)
print os.path.dirname(__file__)
Run Code Online (Sandbox Code Playgroud)

输出结果是奇怪的:

D:\
test.py
D:\test.py
EMPTY
Run Code Online (Sandbox Code Playgroud)

我期待从相同的结果getcwd()path.dirname().

鉴于os.path.abspath = os.path.dirname + os.path.basename,为什么

os.path.dirname(__file__)
Run Code Online (Sandbox Code Playgroud)

返回空?

python

148
推荐指数
6
解决办法
18万
查看次数

如何遍历目录中的文件?

我有一个目录日志文件.我想使用Python脚本处理此目录中的每个文件.

for file in directory:
      # do something
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

python

16
推荐指数
3
解决办法
3万
查看次数

如何递归列出所有文件夹和文件?

如何在python中获取文件夹和文件,包括子目录的文件/文件夹?我需要每个文件/文件夹的绝对路径.

我想重命名所有文件夹和文件.所以我必须先重命名文件夹.

folder
-- file
-- folder1
---- folder1.1
------ file
------ folder1.1.1
-------- file
-- folder2
---- ...
Run Code Online (Sandbox Code Playgroud)

python-2.7

5
推荐指数
1
解决办法
8123
查看次数

递归重命名文件扩展名

我很难创建一个python脚本,它将重命名文件夹中的文件扩展名,并继续在子目录中执行此操作.这是我到目前为止的剧本; 它只能重命名顶级目录中的文件:

#!/usr/bin/python
# Usage: python rename_file_extensions.py

import os
import sys

for filename in os.listdir ("C:\\Users\\username\\Desktop\\test\\"): # parse through file list in the folder "test"

    if filename.find(".jpg") > 0: # if an .jpg is found

            newfilename = filename.replace(".jpg","jpeg") # convert .jpg to jpeg

            os.rename(filename, newfilename) # rename the file
Run Code Online (Sandbox Code Playgroud)

python

1
推荐指数
1
解决办法
3648
查看次数

标签 统计

python ×3

python-2.7 ×1