我正在练习os模块,更具体地说os.walk().我想知道是否有一种更简单/更有效的方法来查找文件的实际路径,因为这会产生一条路径,表明文件在os.walk()首次运行时位于原始文件夹中:
import os
threshold_size = 500
for folder, subfolders, files in os.walk(os.getcwd()):
for file in files:
filePath = os.path.abspath(file)
if os.path.getsize(filePath) >= threshold_size:
print filePath, str(os.path.getsize(filePath))+"kB"
Run Code Online (Sandbox Code Playgroud)
这是我目前的解决方法:
import os
threshold_size = 500
for folder, subfolders, files in os.walk(os.getcwd()):
path = os.path.abspath(folder)
for file in files:
filePath = path + "\\" + file
if os.path.getsize(filePath) >= threshold_size:
print filePath, str(os.path.getsize(filePath))+"kB"
Run Code Online (Sandbox Code Playgroud)
对于shaktimaan,这个:
for folder, subfolders, files in os.walk(os.getcwd()):
for file in files:
filePath = os.path.abspath(file)
print …Run Code Online (Sandbox Code Playgroud) 我想从训练数据集中随机选择10个图像作为测试数据.如果我只将选定的数据复制到目标路径,它就可以工作.但是如果我想删除源数据,它只能删除其中的一些.我尝试了os.remove()和shutil.move()函数,但问题仍然存在.以下是我的脚本:
for label in labels:
training_data_path_ch1 = os.path.join(training_data_folder, label, 'ch1')
test_data_path_ch1 = os.path.join(test_data_folder, label, 'ch1')
training_data_path_ch5 = os.path.join(training_data_folder, label, 'ch5')
test_data_path_ch5 = os.path.join(test_data_folder, label, 'ch5')
ch1_imgs = listdir(training_data_path_ch1)
# Randomly select 10 images
ch1_mask = np.random.choice(len(ch1_imgs), 10)
ch1_selected_imgs = [ch1_imgs[i] for i in ch1_mask]
for selected_img in ch1_selected_imgs:
ch1_img_path = os.path.join(training_data_path_ch1, selected_img)
shutil.copy2(ch1_img_path, test_data_path_ch1)
os.remove(ch1_img_path)
print('Successfully move ' + label + ' ch1 images')
Run Code Online (Sandbox Code Playgroud)
我添加一个图像来显示运行状态.
你可以看到,程序确实可以复制图像并删除一些图像,但为什么它不能删除所有图像?
有任何想法吗?我感谢任何帮助!
在Linux上使用os.getlogin()和os.environ获取当前用户的用户名之间有区别吗?
在不同的时间,我看到有人建议查看环境变量$USER或$LOGNAME,而其他时间os.getlogin()则建议这样做。
所以我很好奇:这是一种首选,还是在某些情况下您会使用一种而不是另一种,或者它们只是做同一件事的两种方式?
所以我必须创建一个运行文件夹,即一个包含一堆我需要运行的python 文件的文件夹。我可以轻松创建此文件夹,并且所有文件都在那里。但是,当我尝试使用运行文件时importlib,python 不会找到它。
我想确保运行的代码实际上是运行文件夹代码,因此我将目录更改为运行文件夹的位置。
abs_path = os.path.abspath("{}".format(run_location))
os.chdir(abs_path)
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print(files)
try:
driver_module = importlib.import_module("main_driver.py")
driver_module.main(config, logger)
except Exception as e:
logger.error("error", str(e))
finish_fail(config, logger)
finish_success(config, logger)
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我只想运行main_driver.py. 上面的输出是:
['PrepareDataframe.py', 'categorical_encoding.py', 'extra_files.zip', 'build_features.py', 'spot_extractor.py', 'dev.ini', 'featuriser.py', 'main_driver.py', 'time_features_extract.py']
Run Code Online (Sandbox Code Playgroud)
显然,main_driver.py位于当前工作目录中,但我收到此错误。
No module named 'main_driver'
Run Code Online (Sandbox Code Playgroud)
追溯:
Traceback (most recent call last):
File "./utils/submit.py", line 292, in <module>
driver_module = importlib.import_module("main_driver")
File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, …Run Code Online (Sandbox Code Playgroud) 当我在控制台(CMD)中输入“winver”时,我将获得我的Windows版本(内部版本号左边的四个数字,例如:1803,1903,1909,2004,20H2)但是我如何在python中获得我的Windows版本?我已经尝试过:
import os
os.system("winver")
input()
Run Code Online (Sandbox Code Playgroud)
但随后它将打开一个新窗口,就像在 cmd 中一样,但我只想打印 winver 而无需其余部分,因此我这样做了:
import os
os.system("Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ReleaseId")
input()
Run Code Online (Sandbox Code Playgroud)
但这里有一个字符串在字符串中的问题。 “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion”
我该如何解决这个问题?请帮忙!
我正在尝试访问父目录中的文本文件,
例如:python脚本在codeSrc中,文本文件在mainFolder中。
G:\mainFolder\codeSrc\fun.py
Run Code Online (Sandbox Code Playgroud)
G:\mainFolder\foo.txt
Run Code Online (Sandbox Code Playgroud)
我目前在python 2.7x中使用此语法,
import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
Run Code Online (Sandbox Code Playgroud)
尽管这可以正常工作,但是有没有更好的方法(更漂亮的:P)呢?
我正在尝试获取os.stat.st_mtime特定目录的最后修改时间()。我的问题是我添加了一些隐藏的元数据文件(它们以开头.)。如果使用,os.stat(directory).st_mtime我得到更新元数据文件的日期,而不是目录中非隐藏文件被修改的日期。我想获取目录中除隐藏元数据文件以外的所有其他文件的最新修改时间。
我认为可以编写自己的函数,大致如下:
for file in folder:
if not file starts with '.':
modified_times.append(os.path.getmtime('/path/to/file')
last_time = most recent of modified_times
Run Code Online (Sandbox Code Playgroud)
但是,是否可以在python中本地执行此操作?还是我需要编写自己的函数,例如上面的伪代码(或类似此问题的东西)?
我想检查一个文件是否存在,以及它是否给我创建的文件夹提供mkdir了下一个更高的数字。不知何故,Error: AttributeError: 'module' object has no attribute 'exist'我不明白为什么该 os 功能对我不起作用。有任何想法吗?
import os
map_name="Example.png"
wk_dir = os.path.dirname(os.path.realpath('__file__'))
dir_name=os.path.splitext(os.path.basename(map_name))[0]
for n in range(0,200):
m=n+1
if os.path.exist(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,n)):
os.mkdir(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,m))
break
Run Code Online (Sandbox Code Playgroud) dir_fd如果我为 的参数分配一个整数os.fwalk(),则会将第四个值添加到 生成的每个元组中list(os.fwalk())。
我知道它们与组织文件和目录的层次结构有关,但我不太明白它们的确切含义。
此外,这些值会根据分配给 dir_fd 的整数而变化,并且总是缺少一个数字(在这种情况下82,请参见下文)。
有任何想法吗?
代码:
import os
os.chdir("/home/test")
inp = str(os.getcwd() + "/input")
l = list(os.fwalk(inp, dir_fd=3))
Run Code Online (Sandbox Code Playgroud)
输出:
[('/home/test/input', ['a', 'b', 'c'], ['d.txt'], 80),
('/home/test/input/a', ['aa'], ['ac.txt', 'ab.txt'], 81),
('/home/test/input/a/aa', [], [], 83),
('/home/test/input/b', [], ['bb.txt', 'bc.txt', 'ba.txt'], 81),
('/home/test/input/c', ['ca'], [], 81),
('/home/test/input/c/ca', ['caa'], ['cab.txt'], 83),
('/home/test/input/c/ca/caa', [], ['caaa.txt'], 84)]
Run Code Online (Sandbox Code Playgroud) 我正在尝试获取所有目录中列出的所有文件的数量以及各个目录中的文件数量。下面是我获取所有目录中文件总数的代码,但我无法获得如何获取单个目录中的文件数。有人可以帮忙吗?
N = 0 #Total count of number of files in all directories
N_c = 0 #Number of documents in each class
for dirpath, dirnames, filenames in os.walk(filePath):
for filename in [f for f in filenames]:
files = [os.path.join(dirpath, filename)]
for f in files:
N+=1
Run Code Online (Sandbox Code Playgroud) 这里是 python 新手。我想创建一个脚本来扫描我的目录,如果文件名中包含特定字符串,那么它将自动移动到我选择的文件夹。已经尝试过这个,但没有运气:
import os
import shutil
import fnmatch
import glob
ffe_path = 'E:/FFE'
new_path = 'E:/FFE/Membership/letters'
keyword = 'membership'
os.chdir('E:/FFE/Membership')
os.mkdir('letters')
source_dir = 'E:/FFE'
dest_dir = 'E:/FFE/Membership/letters'
os.chdir(source_dir)
for top, dirs, files in os.walk(source_dir):
for filename in files:
if not filename.endswith('.docx'):
continue
file_path = os.path.join(top, filename)
with open(file_path, 'r') as f:
if '*membership' in f.read():
shutil.move(file_path, os.path.join(dest_dir, filename))
Run Code Online (Sandbox Code Playgroud)
任何见解将不胜感激。
我有一个函数,我想从用户那里获取路径作为输入,我想在路径中创建一个文件夹。
这是代码片段:
import os
import datetime
def create_folder(name)
current_time = datetime.datetime.now()
folder_name = str(name)+"_("+str(current_time)+")_DATA"
parent_dir = directory_var.get() #getting value from tkinter
print(folder_name)
print(parent_dir)
path = os.path.join(parent_dir, folder_name)
os.mkdir(path)
create_folder("John")
Run Code Online (Sandbox Code Playgroud)
我得到的错误输出是:
John_(2021-08-05 23:43:27.857903)_DATA
C:\app_testing
os.mkdir(path)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:
'C:\\app_testing\\John_(2021-08-05 23:43:27.857903)_DATA'
Run Code Online (Sandbox Code Playgroud)
我需要在给定的 parent_dir 中创建一个新文件夹或目录,文件夹名称为 John_(date)_DATA
一点帮助将不胜感激。谢谢你
我一直在尝试在 google colab 上运行这个单元格,但每次它都说“listdir”未定义。在运行此单元之前,我已在前一个单元中导入了“os”。任何人都可以帮忙找到这里的错误吗?
images = [(train_image_dir+f) for f in listdir(train_image_dir) if isfile(join(train_image_dir, f))]
Run Code Online (Sandbox Code Playgroud)