我正在使用 glob 通过这行代码列出主目录中的所有 python 文件。我也想找到所有 .json 文件和 py 文件,但我找不到任何可以在一行代码中扫描多种文件类型的文件。
for file in glob.glob('/home/mohan/**/*.py', recursive=True):
print(file)
Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的 PC 的特定位置创建一堆目录和子目录。我的过程是这样的:
这是我想出的使用os模块的代码:
def Test():
main_dir = ["FolderA", "FolderB"]
common_dir = ["SubFolder1", "SubFolder2", "SubFolder3"]
for dir1 in main_dir:
if not os.path.isdir(dir1):
for dir2 in common_dir:
os.makedirs("%s/%s" %(dir1,dir2))
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好的方法来完成同样的任务(可能更短、更高效、更 Pythonic)?
我不知道为什么会这样。这是函数:
def scanWallDir(basedir, scansubdirs=True):
wallsOut = []
for entry in os.scandir(basedir):
if entry.is_file():
print(("file " + entry.name))
elif entry.is_dir():
print(("dir " + entry.name))
Run Code Online (Sandbox Code Playgroud)
和错误:
/usr/bin/python2.7 /home/aidan/Code/ulwscs/ulwscs.py
Traceback (most recent call last):
File "/home/aidan/Code/ulwscs/ulwscs.py", line 38, in <module>
scanWallDir("/media/Crossover/Wallpapers")
File "/home/aidan/Code/ulwscs/ulwscs.py", line 11, in scanWallDir
for entry in os.scandir(basedir):
AttributeError: 'module' object has no attribute 'scandir'
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
有谁知道会发生什么?
在下面的示例代码中,我们打开一个文件描述符到sandbox.log,将它作为stdout提供给子进程,然后关闭文件描述符,但子进程仍然可以写入该文件.是subprocess.Popen在内部复制文件描述符吗?将文件描述符传递给子进程后关闭它是否安全?
import subprocess
import os
import time
print 'create or clear sandbox.log'
subprocess.call('touch sandbox.log', shell=True)
subprocess.call('echo "" > sandbox.log', shell=True)
print 'open the file descriptor'
fd = os.open('sandbox.log', os.O_WRONLY)
command = 'sleep 10 && echo "hello world"'
print 'run the command'
p = subprocess.Popen(command, stdout=fd, stderr=subprocess.STDOUT, shell=True)
os.close(fd)
try:
os.close(fd)
except OSError:
print 'fd is already closed'
else:
print 'fd takes some time to close'
if p.poll() is None:
print 'p isnt finished, but fd is closed'
p.wait()
print 'p …Run Code Online (Sandbox Code Playgroud) 为什么a.py用内容调用文件
import os
print('Hi')
os.system('cat a.py')
Run Code Online (Sandbox Code Playgroud)
产生以下输出,如何让它们以正确的顺序打印?
$ python a.py
import os
print('Hi')
os.system('cat a.py')
Hi
Run Code Online (Sandbox Code Playgroud)
你看到cat命令打印到stdout之前print.在Windows 10上的GitBash中运行Python 3.6时会发生.在Ubuntu 17.10上,Python 3.6 不会发生这种情况.
注意:我知道我可以file.readlines()轻松地打印文件内容.这只是一个简单的例子.但是,当运行更复杂的东西时,理解为什么会发生这种情况以及如何解决这个问题变得很重要
我制作了一个程序,最后要求您重新启动。
我import os和用过os.execl(sys.executable, sys.executable, * sys.argv)
但什么也没发生,为什么?
这是代码:
restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
print("\nThe program will be closed...")
sys.exit(0)
Run Code Online (Sandbox Code Playgroud) 通常在此处提交代码时,我会尝试仅包含最少量的代码来演示问题。但是直到写完代码才遇到这个问题,几乎无法调试问题。
我有一段代码可以在一些不同类型之间转换文件。该代码可以正常运行,没有任何问题。它以 ZIP 文件中的 XCI 文件开头,然后将其转换为文件夹。然而,在代码的最后,我试图让我的脚本删除它创建的一些临时文件夹。这会导致一个有点令人困惑的错误,我无法成功地进行故障排除。
import os, shutil, zipfile
from shutil import copyfile
from time import sleep
for fileName in os.listdir("D:/start"):
filePath = "D:/start" + fileName
os.makedirs("C:/Users/Julian/Documents/conversion/extract")
copyfile(filePath, "C:/Users/Julian/Documents/conversion/extract/game.zip")
print("Extracting C:/Users/Julian/Documents/conversion/extract/game.zip")
zip_ref = zipfile.ZipFile("C:/Users/Julian/Documents/conversion/extract/game.zip", 'r')
zip_ref.extractall("C:/Users/Julian/Documents/conversion/extract")
zip_ref.close()
for file in os.listdir("C:/Users/Julian/Documents/conversion/extract"):
if file.endswith(".xci"):
os.rename(os.path.join("C:/Users/Julian/Documents/conversion/extract", file), "C:/Users/Julian/Documents/conversionh/extract/game.xci")
os.system("C:/Users/Julian/Documents/conversion/hactool/hactool.exe -t xci C:/Users/Julian/Documents/conversion/extract/game.xci --outdir=C:/Users/Julian/Documents/conversionh/extract")
fileSizeTupleList = []
largestSize = 0
os.chdir("C:/Users/Julian/Documents/conversion/conversion/secure")
for i in os.listdir(os.curdir):
if os.path.isfile(i):
fileSizeTupleList.append((i, os.path.getsize(i)))
for fileName, fileSize in fileSizeTupleList:
if fileSize > largestSize:
largestSize = fileSize
largestFile …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个程序来轻松处理 IT 请求,并且我已经创建了一个程序来测试我的网络上的 PC 是否在列表中处于活动状态。
为此,我编写了以下代码:
self.btn_Ping.clicked.connect(self.ping)
def ping(self):
hostname = self.listWidget.currentItem().text()
if hostname:
os.system("ping " + hostname + " -t")
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我的主程序冻结,并且在关闭 ping 命令窗口之前我无法执行任何操作。对此我能做什么?我可以使用任何其他命令来尝试 ping 机器而不会使我的主程序冻结吗?
我在 Pop_OS 下使用PyCharm 2020.2.3和Python 3.8.6!20.10(您可能可以像我使用Ubuntu 20.10一样),它无法在/usr/bin或中查看文件/usr/lib。
这是我尝试触摸二进制文件的示例/usr/lib/firefox/firefox。
# main.py
import os
print(os.path.exists('/usr/lib'))
print(os.path.exists('/usr/lib/firefox'))
print(open('/usr/lib/firefox/firefox', 'r'))
Run Code Online (Sandbox Code Playgroud)
从命令行,这是有效的:
>>> python main.py
True
True
<_io.TextIOWrapper name='/usr/lib/firefox/firefox' mode='r' encoding='UTF-8'>
Run Code Online (Sandbox Code Playgroud)
但是当我在 PyCharm 中运行它时,它失败了,如下所示:
True # Can see /usr/lib
False # Cannot see /usr/lib/firefox
Traceback (most recent call last):
File ..., line 5, in <module>
print(open('/usr/lib/firefox/firefox', 'r'))
FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib/firefox/firefox'
Run Code Online (Sandbox Code Playgroud)
以下是以下权限usr/bin/firefox:
>>> ls -ld firefox
drwxr-xr-x …Run Code Online (Sandbox Code Playgroud) 我正在开发一个程序,需要调用另一个 python 脚本并截断当前文件的执行。我尝试使用 os.close() 函数执行相同的操作。如下:
def call_otherfile(self):
os.system("python file2.py") #Execute new script
os.close() #close Current Script
Run Code Online (Sandbox Code Playgroud)
使用上面的代码我可以打开第二个文件,但无法关闭当前的文件。我知道我是一个愚蠢的错误,但无法弄清楚它是什么。
python-os ×10
python ×9
python-3.x ×4
directory ×2
permissions ×2
python-2.7 ×2
file ×1
filepath ×1
git-bash ×1
glob ×1
pycharm ×1
python-3.6 ×1
restart ×1
scandir ×1
shutil ×1
unix ×1