如何在Python 3.3.3中导入一个文件 [英] how to import a file in python 3.3.3

查看:180
本文介绍了如何在Python 3.3.3中导入一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一个文件加载一个数组(现在有一段时间了,并且经历了很多堆栈溢出问题),但我无法得到最简单的工作。这是我得到的错误之一:

 >>> inp = open('C:\Users\user\Documents\w-game\run\map1.txt','r')
SyntaxError:(unicode error)'unicodeescape'codec can在位置2-3解码字节
:截断\UXXXXXXXX转义

没有得到那个错误。它根本找不到该文件,虽然我确定它在那里,它是一个文本文件。



是否有人知道这是怎么回事,或者如果这个方法在Python 3.3.3中不起作用的话?

解决方案

错误不在文件中,而是在文件名字符串中。您需要在您的文件名中跳过反斜杠;使用原始字符串:

  open(r'C:\Users\user\Documents\w- game\\ \\ run\map1.txt')

因为 \Uhhhhhhhh


















$ b $ $ b

  open('C:\\ Users \\\\\\\\\\\\\\ users map1.txt')

或使用转发斜线:

  open('C:/Users/user/Documents/w-game/run/map1.txt')

 > >>打印('C:\ Users')
文件< stdin>,第1行
SyntaxError:(unicode error)'unicodeescape'编解码器无法解码位置2-3中的字节:截断\UXXXXXXXX转义
>>> print(r'C:\Users')
C:\Users
>>> print('C:\\Users')
C:\Users
>>> print('C:/ Users')
C:/ Users


I am trying to load a array from another file(for a while now, and have been going through a lot of Stack Overflow Questions), but I can't get the easiest things to work. This is one of the errors I got:

 >>> inp = open ('C:\Users\user\Documents\w-game\run\map1.txt','r')
 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes 
 in position 2-3:       truncated \UXXXXXXXX escape

Sometimes I didn't get that error. It simply couldn't find the file, although I am sure it was there and it was a text file.

Does anybody know what is up or if this method doesn't work in python 3.3.3 anymore?

解决方案

The error is not in the file, but in the filename string. You need to escape the backslashes in your filename; use a raw string:

open(r'C:\Users\user\Documents\w-game\run\map1.txt')

because \Uhhhhhhhh is a unicode escape code for a character outside of the BMP.

You can also double the slashes:

open('C:\\Users\\user\\Documents\\w-game\\run\\map1.txt')

or use forward slashes:

open('C:/Users/user/Documents/w-game/run/map1.txt')

Demo:

>>> print('C:\Users')
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> print(r'C:\Users')
C:\Users
>>> print('C:\\Users')
C:\Users
>>> print('C:/Users')
C:/Users

这篇关于如何在Python 3.3.3中导入一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆