python读取文件的目录问题

nidodo1 2018-09-10 11:56:13
刚开始学python,是windows环境,在做习题和抄书本例子的时候都遇到这个目录问题,都要补全文件所在目录的全路径才能正常读取,用相对路径都提示无法打开,比如这个例子, self.image=pygame.image.load('images/ship.bmp') 这个不科学啊,请问怎么解决?
...全文
456 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianfang 2018-09-12
  • 打赏
  • 举报
回复
让自己的程序兼容性好,设置一个 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 然后都从这个路径+相对路径
tianfang 2018-09-12
  • 打赏
  • 举报
回复
自己设定一下吧
nidodo1 2018-09-12
  • 打赏
  • 举报
回复
引用 3 楼 tianfang 的回复:
https://www.pygame.org/docs/ref/image.html 官方文档:
You should use os.path.join() for compatibility.

eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))

我大概知道原因了:
我用的VS2017,配置的python,它工作目录在vs的安装程序下,找文件也是在这个工作目录下找,除非设置了全路径,所以一直找不到,我用pycharm就正常了。
不知道怎么能让vs2017把工作目录变成程序文件所在目录?
nidodo1 2018-09-11
  • 打赏
  • 举报
回复
引用 3 楼 tia[color=#333300
nfang 的回复:]
https://www.pygame.org/docs/ref/image.html 官方文档:
You should use os.path.join() for compatibility.

eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))

试过了,也不行啊
File "D:\vs\python\alien\ship.py", line 10, in __init__
self.image=pygame.image.load(os.path.join('images','ship.bmp'))
pygame.error: Couldn't open images\ship.bmp
错误提示里的目录是对的,就是报错

代码:
import pygame
import os
class Ship():
def __init__(self,ai_settings,screen):
#初始化飞船并设置其初始位置
self.screen=screen
self.ai_settings=ai_settings
#加载飞船图像并获取其外接矩形
# self.image=pygame.image.load(r"D:\vs\python\alien\images\ship.bmp")
self.image=pygame.image.load(os.path.join('images','ship.bmp'))
self.rect=self.image.get_rect()
self.screen_rect=screen.get_rect()

#将每艘新飞船放在屏幕底部中央
self.rect.centerx=self.screen_rect.centerx
self.rect.bottom=self.screen_rect.bottom
self.center=float(self.rect.centerx)
self.moving_right=False
self.moving_left=False
def update(self):
#根据移动标志调整飞船的位置
if self.moving_right and self.rect.right<self.screen_rect.right:

self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left>0:
self.center -= self.ai_settings.ship_speed_factor

self.rect.centerx=self.center
def blitme(self):
#在指定位置绘制飞船
self.screen.blit(self.image,self.rect)

tianfang 2018-09-11
  • 打赏
  • 举报
回复
https://www.pygame.org/docs/ref/image.html 官方文档: You should use os.path.join() for compatibility. eg. asurf = pygame.image.load(os.path.join('data', 'bla.png'))
nidodo1 2018-09-11
  • 打赏
  • 举报
回复
引用 1 楼 tianfang 的回复:
哪个代码发生了错误,错误信息是什么?全路径这么写的

https://blog.csdn.net/weixin_39449570/article/details/78436705
就是这个问题,这样解决是可以解决,但不能总指定全路径啊
tianfang 2018-09-10
  • 打赏
  • 举报
回复
哪个代码发生了错误,错误信息是什么?全路径这么写的

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧