标签归档:python-3.x

如何在Python Shell中知道/更改当前目录?

问题:如何在Python Shell中知道/更改当前目录?

我在Windows 7上使用Python 3.2。打开Python Shell时,如何知道当前目录是什么,以及如何将其更改为模块所在的另一个目录?

I am using Python 3.2 on Windows 7. When I open the Python shell, how can I know what the current directory is and how can I change it to another directory where my modules are?


回答 0

您可以使用该os模块。

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

但是,如果要查找其他模块:您可以PYTHONPATH在Linux下设置一个名为的环境变量,就像

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

然后,解释器也在此位置搜索imported模块。我想Windows下的名称会相同,但是不知道如何更改。

编辑

在Windows下:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(摘自http://docs.python.org/using/windows.html

编辑2

…甚至更好:使用virtualenvvirtualenv_wrapper,这将允许您创建一个开发环境,在其中您可以根据需要添加模块路径(add2virtualenv),而不会污染安装或“正常”的工作环境。

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it’s about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don’t know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

… and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or “normal” working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html


回答 1

你要

import os
os.getcwd()
os.chdir('..')

you want

import os
os.getcwd()
os.chdir('..')

回答 2

>>> import os
>>> os.system('cd c:\mydir')

实际上,os.system()可以执行Windows命令提示符可以执行的任何命令,而不仅仅是更改dir。

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.


回答 3

更改当前目录不是处理Python中的模块的方法。

相反,请参阅有关模块搜索路径的文档获取Python如何找到要导入的模块的信息。

以下是“ 标准模块”部分的相关内容:

变量sys.path是一个字符串列表,该字符串确定解释器对模块的搜索路径。它初始化为从环境变量PYTHONPATH提取的默认路径,或者如果未设置PYTHONPATH则从内置的默认路径初始化。您可以使用标准列表操作对其进行修改:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

在回答有关获取和设置当前目录的原始问题时:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.

Changing the current directory is not the way to deal with finding modules in Python.

Rather, see the docs for The Module Search Path for how Python finds which module to import.

Here is a relevant bit from Standard Modules section:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

In answer your original question about getting and setting the current directory:

>>> help(os.getcwd)

getcwd(...)
    getcwd() -> path

    Return a string representing the current working directory.

>>> help(os.chdir)

chdir(...)
    chdir(path)

    Change the current working directory to the specified path.

回答 4

在python中更改当前工作目录的最简单方法是使用“ os”包。下面是Windows计算机的示例:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

The easiest way to change the current working directory in python is using the ‘os’ package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

回答 5

如果您import os可以os.getcwd用来获取当前的工作目录,并且可以os.chdir用来更改目录

If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory


回答 6

您可以尝试以下方法:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"

You can try this:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"



builtins.TypeError:必须为str,而不是字节

问题:builtins.TypeError:必须为str,而不是字节

我已经将脚本从Python 2.7转换为3.2,并且有一个错误。

# -*- coding: utf-8 -*-
import time
from datetime import date
from lxml import etree
from collections import OrderedDict

# Create the root element
page = etree.Element('results')

# Make a new document tree
doc = etree.ElementTree(page)

# Add the subelements
pageElement = etree.SubElement(page, 'Country',Tim = 'Now', 
                                      name='Germany', AnotherParameter = 'Bye',
                                      Code='DE',
                                      Storage='Basic')
pageElement = etree.SubElement(page, 'City', 
                                      name='Germany',
                                      Code='PZ',
                                      Storage='Basic',AnotherParameter = 'Hello')
# For multiple multiple attributes, use as shown above

# Save to XML file
outFile = open('output.xml', 'w')
doc.write(outFile) 

在最后一行,我得到了这个错误:

builtins.TypeError: must be str, not bytes
File "C:\PythonExamples\XmlReportGeneratorExample.py", line 29, in <module>
  doc.write(outFile)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 1853, in lxml.etree._ElementTree.write (src/lxml/lxml.etree.c:44355)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 478, in lxml.etree._tofilelike (src/lxml/lxml.etree.c:90649)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 282, in lxml.etree._ExceptionContext._raise_if_stored (src/lxml/lxml.etree.c:7972)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 378, in lxml.etree._FilelikeWriter.write (src/lxml/lxml.etree.c:89527)

我已经安装了Python 3.2,并且已经安装了lxml-2.3.win32-py3.2.exe。

在Python 2.7上可以使用。

I’ve converted my scripts from Python 2.7 to 3.2, and I have a bug.

# -*- coding: utf-8 -*-
import time
from datetime import date
from lxml import etree
from collections import OrderedDict

# Create the root element
page = etree.Element('results')

# Make a new document tree
doc = etree.ElementTree(page)

# Add the subelements
pageElement = etree.SubElement(page, 'Country',Tim = 'Now', 
                                      name='Germany', AnotherParameter = 'Bye',
                                      Code='DE',
                                      Storage='Basic')
pageElement = etree.SubElement(page, 'City', 
                                      name='Germany',
                                      Code='PZ',
                                      Storage='Basic',AnotherParameter = 'Hello')
# For multiple multiple attributes, use as shown above

# Save to XML file
outFile = open('output.xml', 'w')
doc.write(outFile) 

On the last line, I got this error:

builtins.TypeError: must be str, not bytes
File "C:\PythonExamples\XmlReportGeneratorExample.py", line 29, in <module>
  doc.write(outFile)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 1853, in lxml.etree._ElementTree.write (src/lxml/lxml.etree.c:44355)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 478, in lxml.etree._tofilelike (src/lxml/lxml.etree.c:90649)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 282, in lxml.etree._ExceptionContext._raise_if_stored (src/lxml/lxml.etree.c:7972)
File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 378, in lxml.etree._FilelikeWriter.write (src/lxml/lxml.etree.c:89527)

I’ve installed Python 3.2, and I’ve installed lxml-2.3.win32-py3.2.exe.

On Python 2.7 it works.


回答 0

输出文件应处于二进制模式。

outFile = open('output.xml', 'wb')

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

回答 1

将二进制文件转换为base64,反之亦然。在python 3.5.2中证明

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

如何卸载使用pip install –user安装的软件包

问题:如何卸载使用pip install –user安装的软件包

--userpip 有一个选项,可以为每个用户安装Python软件包:

pip install --user [python-package-name]

我使用此选项在没有root访问权限的服务器上安装软件包。我现在需要的是在当前用户上卸载已安装的软件包。我试图执行以下命令:

pip uninstall --user [python-package-name]

但是我得到了:

no such option: --user

pip install --user除了手动查找和删除软件包外,如何卸载与之一起安装的软件包?

我发现这篇文章

pip无法从每个用户的站点软件包目录中卸载

描述了不支持从用户目录卸载软件包。根据文章,如果正确实施,则使用

pip uninstall [package-name]

安装的软件包也将在用户目录中搜索。但是对我来说仍然是一个问题。如果在系统范围和每个用户都安装了相同的软件包,该怎么办?如果有人需要针对特定​​用户目录怎么办?

There is a --user option for pip which can install a Python package per user:

pip install --user [python-package-name]

I used this option to install a package on a server for which I do not have root access. What I need now is to uninstall the installed package on the current user. I tried to execute this command:

pip uninstall --user [python-package-name]

But I got:

no such option: --user

How can I uninstall a package that I installed with pip install --user, other than manually finding and deleting the package?

I’ve found this article

pip cannot uninstall from per-user site-packages directory

which describes that uninstalling packages from user directory does not supported. According to the article if it was implemented correctly then with

pip uninstall [package-name]

the package that was installed will be also searched in user directories. But a problem still remains for me. What if the same package was installed both system-wide and per-user? What if someone needs to target a specific user directory?


回答 0

在Linux上使用Python 3.5和pip 7.1.2测试了这一情况之后,情况似乎是这样的:

  • pip install --user somepackage可以使用进行安装$HOME/.local和卸载pip uninstall somepackage

  • 无论是否somepackage同时在全系统范围内安装,都是如此。

  • 如果在两个地方都安装了该软件包,则只​​会卸载本地软件包。要使用卸载系统范围的软件包pip,请先在本地将其卸载,然后使用root特权再次运行相同的卸载命令。

  • 除了预定义的用户安装目录外,pip install --target somedir somepackage还将软件包安装到中somedir。无法使用从这样的位置卸载软件包pip。(但是在Github上实现了一个有点旧的未合并的pull请求,它实现了pip uninstall --target。)

  • 由于pip将要卸载的唯一位置是系统范围的和预定义的本地用户,因此您需要以pip uninstall相应用户身份运行才能从给定用户的本地安装目录中卸载。

Having tested this using Python 3.5 and pip 7.1.2 on Linux, the situation appears to be this:

  • pip install --user somepackage installs to $HOME/.local, and uninstalling it does work using pip uninstall somepackage.

  • This is true whether or not somepackage is also installed system-wide at the same time.

  • If the package is installed at both places, only the local one will be uninstalled. To uninstall the package system-wide using pip, first uninstall it locally, then run the same uninstall command again, with root privileges.

  • In addition to the predefined user install directory, pip install --target somedir somepackage will install the package into somedir. There is no way to uninstall a package from such a place using pip. (But there is a somewhat old unmerged pull request on Github that implements pip uninstall --target.)

  • Since the only places pip will ever uninstall from are system-wide and predefined user-local, you need to run pip uninstall as the respective user to uninstall from a given user’s local install directory.


回答 1

在MacOS上卸载软件包’oauth2client’的示例:

pip uninstall oauth2client

example to uninstall package ‘oauth2client’ on MacOS:

pip uninstall oauth2client

回答 2

但是,对于pip install --user some_pkg 在虚拟环境中使用的人员要小心。

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

在这种情况下,您必须停用当前的虚拟环境,然后使用相应的python/ pip可执行文件列出或卸载用户站点软件包:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

请注意,此问题是几年前报告的。似乎当前的结论是:在虚拟环境中--user无效pip,因为用户位置对于虚拟环境而言实际上没有任何意义。

Be careful though, for those who using pip install --user some_pkg inside a virtual environment.

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

In this case, you have to deactivate the current virtual environment, then use the corresponding python/pip executable to list or uninstall the user site packages:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

Note that this issue was reported few years ago. And it seems that the current conclusion is: --user is not valid inside a virtual env’s pip, since a user location doesn’t really make sense for a virtual environment.


回答 3

我认为可以卸载带有--userflag的软件包。这个为我工作;

pip freeze --user | xargs pip uninstall -y

对于python 3;

pip3 freeze --user | xargs pip3 uninstall -y

但是以某种方式,这些命令不会卸载setuptools和pip。在这些命令之后(如果您确实想要干净的python),可以使用以下命令删除它们:

pip uninstall setuptools && pip uninstall pip

I think it’s possible to uninstall packages installed with --user flag. This one worked for me;

pip freeze --user | xargs pip uninstall -y

For python 3;

pip3 freeze --user | xargs pip3 uninstall -y

But somehow these commands don’t uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;

pip uninstall setuptools && pip uninstall pip


回答 4

答案尚不可行。您必须手动将其删除。

The answer is Not possible yet. You have to remove it manually.


回答 5

正如@ thomas-lotze提到的那样,由于没有相应的–user选项,当前pip工具无法执行此操作。但是我发现我可以检入〜/ .local / bin并查找特定的pip#。#,在我看来它对应于–user选项。

就我而言:

antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

然后只需卸载特定的pip版本即可。

As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding –user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the –user option.

In my case:

antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip  pip2  pip2.7  pip3  pip3.5

And then just uninstall with the specific pip version.


回答 6

我正在运行Anaconda 4.3.22版和python3.6.1环境,并且遇到了此问题。这是历史记录和修复方法:

pip uninstall opencv-python # -- the original step. failed.

ImportError: DLL load failed: The specified module could not be found.

我在python3.6环境中执行了此操作,并收到此错误。

python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.

接下来,我尝试下载python3.6并将python3.dll放入该文件夹和各个文件夹中。没有改变。

最后,它解决了:

pip uninstall opencv-python

(仍然安装了另一个conda-forge版本)。这仅留下了conda版本,并且在3.6版本中有效。

>>>import cv2
>>>

加工!

I am running Anaconda version 4.3.22 and a python3.6.1 environment, and had this problem. Here’s the history and the fix:

pip uninstall opencv-python # -- the original step. failed.

ImportError: DLL load failed: The specified module could not be found.

I did this into my python3.6 environment and got this error.

python -m pip install opencv-python # same package as above.
conda install -c conda-forge opencv # separate install parallel to opencv
pip-install opencv-contrib-python # suggested by another user here. doesn't resolve it.

Next, I tried downloading python3.6 and putting the python3.dll in the folder and in various folders. nothing changed.

finally, this fixed it:

pip uninstall opencv-python

(the other conda-forge version is still installed) This left only the conda version, and that works in 3.6.

>>>import cv2
>>>

working!


TypeError:缺少1个必需的位置参数:’self’

问题:TypeError:缺少1个必需的位置参数:’self’

我是python新手,碰壁了。我遵循了一些教程,但无法克服错误:

Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
    p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'

我检查了一些教程,但似乎与我的代码没有什么不同。我唯一能想到的是python 3.3需要不同的语法。

主要技巧:

# test script

from lib.pump import Pump

print ("THIS IS A TEST OF PYTHON") # this prints

p = Pump.getPumps()

print (p)

泵类:

import pymysql

class Pump:

    def __init__(self):
        print ("init") # never prints


    def getPumps(self):
                # Open database connection
                # some stuff here that never gets executed because of error

如果我正确理解,“自我”将自动传递给构造函数和方法。我在这里做错了什么?

我正在将Windows 8与python 3.3.2一起使用

I am new to python and have hit a wall. I followed several tutorials but cant get past the error:

Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
    p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'

I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that python 3.3 requires different syntax.

main scipt:

# test script

from lib.pump import Pump

print ("THIS IS A TEST OF PYTHON") # this prints

p = Pump.getPumps()

print (p)

Pump class:

import pymysql

class Pump:

    def __init__(self):
        print ("init") # never prints


    def getPumps(self):
                # Open database connection
                # some stuff here that never gets executed because of error

If I understand correctly “self” is passed to the constructor and methods automatically. What am I doing wrong here?

I am using windows 8 with python 3.3.2


回答 0

您需要在此处实例化一个类实例。

p = Pump()
p.getPumps()

小例子-

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example –

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

回答 1

您需要先对其进行初始化:

p = Pump().getPumps()

You need to initialize it first:

p = Pump().getPumps()

回答 2

比我在这里看到的所有其他解决方案都有效并且更简单:

Pump().getPumps()

如果您不需要重用类实例,那么这很好。在Python 3.7.3上测试。

Works and is simpler than every other solution I see here :

Pump().getPumps()

This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.


回答 3

您也可以通过过早地接受PyCharm的建议来注释方法@staticmethod来获得此错误。删除注释。

You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.


回答 4

python中的‘self’关键字类似于c ++ / java / c#中的‘this’关键字。

在python 2中,它是由编译器隐式完成的(yes python does compilation internally)。只是在python 3中,您需要explicitly在构造函数和成员函数中提及它。例:

 class Pump():
 //member variable
 account_holder
 balance_amount

   // constructor
   def __init__(self,ah,bal):
   |    self.account_holder = ah
   |    self.balance_amount = bal

   def getPumps(self):
   |    print("The details of your account are:"+self.account_number + self.balance_amount)

 //object = class(*passing values to constructor*)
 p = Pump("Tahir",12000)
 p.getPumps()

The self keyword in Python is analogous to this keyword in C++ / Java / C#.

In Python 2 it is done implicitly by the compiler (yes Python does compilation internally). It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:

 class Pump():
 //member variable
 account_holder
 balance_amount

   // constructor
   def __init__(self,ah,bal):
   |    self.account_holder = ah
   |    self.balance_amount = bal

   def getPumps(self):
   |    print("The details of your account are:"+self.account_number + self.balance_amount)

 //object = class(*passing values to constructor*)
 p = Pump("Tahir",12000)
 p.getPumps()

“ for line in…”导致UnicodeDecodeError:’utf-8’编解码器无法解码字节

问题:“ for line in…”导致UnicodeDecodeError:’utf-8’编解码器无法解码字节

这是我的代码,

for line in open('u.item'):
#read each line

每当我运行此代码时,都会出现以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte

我试图解决这个问题,并在open()中添加了一个额外的参数,代码看起来像;

for line in open('u.item', encoding='utf-8'):
#read each line

但是,它再次给出相同的错误。那我该怎么办!请帮忙。

Here is my code,

for line in open('u.item'):
#read each line

whenever I run this code it gives the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte

I tried to solve this and add an extra parameter in open(), the code looks like;

for line in open('u.item', encoding='utf-8'):
#read each line

But again it gives the same error. what should I do then! Please help.


回答 0

正如Mark Ransom所建议的,我找到了解决该问题的正确编码。编码为“ ISO-8859-1”,因此替换open("u.item", encoding="utf-8")open('u.item', encoding = "ISO-8859-1")可以解决该问题。

As suggested by Mark Ransom, I found the right encoding for that problem. The encoding was "ISO-8859-1", so replacing open("u.item", encoding="utf-8") with open('u.item', encoding = "ISO-8859-1") will solve the problem.


回答 1

同样对我有用,ISO 8859-1将节省很多,哈哈哈,主要是如果使用语音识别API的话

例:

file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");

Also worked for me, ISO 8859-1 is going to save a lot, hahaha, mainly if using Speech Recognition API’s

Example:

file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");

回答 2

您的文件实际上并不包含utf-8编码的数据,而是包含其他一些编码。弄清楚编码是什么,并在open调用中使用它。

例如,在Windows-1252编码中,0xe9字符为é

Your file doesn’t actually contain utf-8 encoded data, it contains some other encoding. Figure out what that encoding is and use it in the open call.

In Windows-1252 encoding for example the 0xe9 would be the character é.


回答 3

尝试使用熊猫阅读

pd.read_csv('u.item', sep='|', names=m_cols , encoding='latin-1')

Try this to read using pandas

pd.read_csv('u.item', sep='|', names=m_cols , encoding='latin-1')

回答 4

如果使用Python 2以下将解决方案:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # do something

由于encodingparameter不适用于open(),因此您将收到以下错误:

TypeError:“ encoding”是此函数的无效关键字参数

If you are using Python 2 the following will the solution:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # do something

Because encoding parameter doesn’t work with open(), you will be getting the following error:

TypeError: 'encoding' is an invalid keyword argument for this function

回答 5

您可以使用以下方法解决问题:

for line in open(your_file_path, 'rb'):

‘rb’以二进制模式读取文件。在这里阅读更多。希望这会有所帮助!

You could resolve the problem with:

for line in open(your_file_path, 'rb'):

‘rb’ is reading file in binary mode. Read more here. Hope this will help!


回答 6

这有效:

open('filename', encoding='latin-1')

要么:

open('filename',encoding="IS0-8859-1")

This works:

open('filename', encoding='latin-1')

or:

open('filename',encoding="ISO-8859-1")

回答 7

如果有人在寻找这些,这是在Python 3中转换CSV文件的示例:

try:
    inputReader = csv.reader(open(argv[1], encoding='ISO-8859-1'), delimiter=',',quotechar='"')
except IOError:
    pass

If someone looking for these, this is an example for converting a CSV file in Python 3:

try:
    inputReader = csv.reader(open(argv[1], encoding='ISO-8859-1'), delimiter=',',quotechar='"')
except IOError:
    pass

回答 8

有时,open(filepath)在其中filepath实际上不是一个文件会得到同样的错误,所以,首先要确保你试图打开的文件存在:

import os
assert os.path.isfile(filepath)

希望这会有所帮助。

Sometimes when open(filepath) in which filepath actually is not a file would get the same error, so firstly make sure the file you’re trying to open exists:

import os
assert os.path.isfile(filepath)

hope this will help.


回答 9

您可以这样尝试:

open('u.item', encoding='utf8', errors='ignore')

you can try this way:

open('u.item', encoding='utf8', errors='ignore')

如何在python-3.x中使用字典格式化字符串?

问题:如何在python-3.x中使用字典格式化字符串?

我非常喜欢使用字典来格式化字符串。它可以帮助我阅读所使用的字符串格式,也可以利用现有的字典。例如:

class MyClass:
    def __init__(self):
        self.title = 'Title'

a = MyClass()
print 'The title is %(title)s' % a.__dict__

path = '/path/to/a/file'
print 'You put your file here: %(path)s' % locals()

但是我无法弄清楚python 3.x语法是否可以这样做(或者甚至可以)。我想做以下

# Fails, KeyError 'latitude'
geopoint = {'latitude':41.123,'longitude':71.091}
print '{latitude} {longitude}'.format(geopoint)

# Succeeds
print '{latitude} {longitude}'.format(latitude=41.123,longitude=71.091)

I am a big fan of using dictionaries to format strings. It helps me read the string format I am using as well as let me take advantage of existing dictionaries. For example:

class MyClass:
    def __init__(self):
        self.title = 'Title'

a = MyClass()
print 'The title is %(title)s' % a.__dict__

path = '/path/to/a/file'
print 'You put your file here: %(path)s' % locals()

However I cannot figure out the python 3.x syntax for doing the same (or if that is even possible). I would like to do the following

# Fails, KeyError 'latitude'
geopoint = {'latitude':41.123,'longitude':71.091}
print '{latitude} {longitude}'.format(geopoint)

# Succeeds
print '{latitude} {longitude}'.format(latitude=41.123,longitude=71.091)

回答 0

由于问题是特定于Python 3的,因此这里使用的从Python 3.6开始可用的新f字符串语法

>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091

注意外部单引号和内部双引号(您也可以采用其他方法)。

Since the question is specific to Python 3, here’s using the new f-string syntax, available since Python 3.6:

>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091

Note the outer single quotes and inner double quotes (you could also do it the other way around).


回答 1

这对你有好处吗?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

Is this good for you?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

回答 2

要将字典解压缩为关键字参数,请使用**。此外,新型格式支持引用对象的属性和映射项:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

回答 3

由于Python 3.0和3.1已停产,而且没有人使用它们,因此您可以并且应该使用str.format_map(mapping)(Python 3.2+):

与相似str.format(**mapping)除了直接使用映射而不将其复制到dict。例如,如果映射是dict子类,则这很有用。

这意味着您可以使用例如defaultdict为丢失的键设置(并返回)默认值的a:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

即使提供的映射是dict,而不是子类,也可能会稍快一些。

鉴于给定,差异并不大

>>> d = dict(foo='x', bar='y', baz='z')

然后

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

约比10 ns(2%)快

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

在我的Python 3.4.3上。当字典中有更多键时,差异可能会更大,并且


注意,格式语言比它灵活得多。它们可以包含索引表达式,属性访问等,因此您可以格式化整个对象或其中两个:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

从3.6开始,您也可以使用插值字符串:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

您只需要记住在嵌套引号中使用其他引号字符。这种方法的另一个好处是,它比调用格式化方法要快得多

As Python 3.0 and 3.1 are EOL’ed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo='x', bar='y', baz='z')

then

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

is about 10 ns (2 %) faster than

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and


Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

Starting from 3.6 you can use the interpolated strings too:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.


回答 4

print("{latitude} {longitude}".format(**geopoint))
print("{latitude} {longitude}".format(**geopoint))

回答 5

Python 2语法也可以在Python 3中使用:

>>> class MyClass:
...     def __init__(self):
...         self.title = 'Title'
... 
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>> 
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file

The Python 2 syntax works in Python 3 as well:

>>> class MyClass:
...     def __init__(self):
...         self.title = 'Title'
... 
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>> 
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file

回答 6

geopoint = {'latitude':41.123,'longitude':71.091}

# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method  (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll
geopoint = {'latitude':41.123,'longitude':71.091}

# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method  (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll

回答 7

大多数答案仅格式化dict的值。

如果还要将密钥格式化为字符串,则可以使用dict.items()

geopoint = {'latitude':41.123,'longitude':71.091}
print("{} {}".format(*geopoint.items()))

输出:

(“纬度”,41.123)(“经度”,71.091)

如果要以套利方式格式化,即不显示元组之类的键值:

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

输出:

纬度为41.123,经度为71.091

Most answers formatted only the values of the dict.

If you want to also format the key into the string you can use dict.items():

geopoint = {'latitude':41.123,'longitude':71.091}
print("{} {}".format(*geopoint.items()))

Output:

(‘latitude’, 41.123) (‘longitude’, 71.091)

If you want to format in an arbitry way, that is, not showing the key-values like tuples:

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

Output:

latitude is 41.123 and longitude is 71.091


将JSON字符串转换为字典未列出

问题:将JSON字符串转换为字典未列出

我正在尝试传递JSON文件并将数据转换成字典。

到目前为止,这是我所做的:

import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)

我期望json1_data是一种dict类型,但是list当我使用进行检查时,它实际上是作为一种类型出现的type(json1_data)

我想念什么?我需要将它作为字典,以便可以访问其中一个键。

I am trying to pass in a JSON file and convert the data into a dictionary.

So far, this is what I have done:

import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)

I’m expecting json1_data to be a dict type but it actually comes out as a list type when I check it with type(json1_data).

What am I missing? I need this to be a dictionary so I can access one of the keys.


回答 0

JSON是一个内部有单个对象的数组,因此当您读入JSON时,会得到一个内部带有字典的列表。您可以通过访问列表中的项目0来访问字典,如下所示:

json1_data = json.loads(json1_str)[0]

现在,您可以按预期访问存储在数据点中的数据

datapoints = json1_data['datapoints']

我还有一个问题,是否有人可以咬:我正在尝试获取这些数据点(即datapoints [0] [0])中第一个元素的平均值。只是列出它们,我尝试做datapoints [0:5] [0],但我得到的只是两个元素的第一个数据点,而不是想要获取仅包含第一个元素的前5个数据点。有没有办法做到这一点?

datapoints[0:5][0]并没有达到您的期望。datapoints[0:5]返回仅包含前5个元素的新列表切片,然后[0]在其末尾添加将仅从结果列表切片中获取第一个元素。您需要使用以获得列表结果的方法:

[p[0] for p in datapoints[0:5]]

这是一种计算均值的简单方法:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

如果您愿意安装NumPy,那么它甚至更容易:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

,运算符与NumPy数组的切片语法一起使用会产生您最初期望的与列表切片相同的行为。

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn’t do what you’re expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here’s a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you’re willing to install NumPy, then it’s even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy’s arrays has the behavior you were originally expecting with the list slices.


回答 1

这是一个简单的代码片段,可json从字典中读取文本文件。请注意,您的json文件必须遵循json标准,因此它必须具有"双引号而不是'单引号。

您的JSON dump.txt文件:

{"test":"1", "test2":123}

Python脚本:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

Here is a simple snippet that read’s in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

回答 2

您可以使用以下内容:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

回答 3

将JSON数据加载到Dictionary中的最好方法是可以使用内置的json加载器。

以下是可以使用的示例代码段。

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])

The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.

Below is the sample snippet that can be used.

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])

回答 4

我正在使用针对REST API的Python代码,因此这是针对从事类似项目的人员的。

我使用POST请求从URL提取数据,原始输出为JSON。由于某种原因,输出已经是字典,而不是列表,并且我能够立即引用嵌套的字典键,如下所示:

datapoint_1 = json1_data['datapoints']['datapoint_1']

其中datapoint_1在数据点字典中。

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I’m able to refer to the nested dictionary keys right away, like this:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.


回答 5

从get方法使用javascript ajax传递数据

    **//javascript function    
    function addnewcustomer(){ 
    //This function run when button click
    //get the value from input box using getElementById
            var new_cust_name = document.getElementById("new_customer").value;
            var new_cust_cont = document.getElementById("new_contact_number").value;
            var new_cust_email = document.getElementById("new_email").value;
            var new_cust_gender = document.getElementById("new_gender").value;
            var new_cust_cityname = document.getElementById("new_cityname").value;
            var new_cust_pincode = document.getElementById("new_pincode").value;
            var new_cust_state = document.getElementById("new_state").value;
            var new_cust_contry = document.getElementById("new_contry").value;
    //create json or if we know python that is call dictionary.        
    var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
    //apply stringfy method on json
            data = JSON.stringify(data);
    //insert data into database using javascript ajax
            var send_data = new XMLHttpRequest();
            send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
            send_data.send();

            send_data.onreadystatechange = function(){
              if(send_data.readyState==4 && send_data.status==200){
                alert(send_data.responseText);
              }
            }
          }

django意见

    def addNewCustomer(request):
    #if method is get then condition is true and controller check the further line
        if request.method == "GET":
    #this line catch the json from the javascript ajax.
            cust_info = request.GET.get("customerinfo")
    #fill the value in variable which is coming from ajax.
    #it is a json so first we will get the value from using json.loads method.
    #cust_name is a key which is pass by javascript json. 
    #as we know json is a key value pair. the cust_name is a key which pass by javascript json
            cust_name = json.loads(cust_info)['cust_name']
            cust_cont = json.loads(cust_info)['cust_cont']
            cust_email = json.loads(cust_info)['cust_email']
            cust_gender = json.loads(cust_info)['cust_gender']
            cust_cityname = json.loads(cust_info)['cust_cityname']
            cust_pincode = json.loads(cust_info)['cust_pincode']
            cust_state = json.loads(cust_info)['cust_state']
            cust_contry = json.loads(cust_info)['cust_contry']
    #it print the value of cust_name variable on server
            print(cust_name)
            print(cust_cont)
            print(cust_email)
            print(cust_gender)
            print(cust_cityname)
            print(cust_pincode)
            print(cust_state)
            print(cust_contry)
            return HttpResponse("Yes I am reach here.")**

pass the data using javascript ajax from get methods

    **//javascript function    
    function addnewcustomer(){ 
    //This function run when button click
    //get the value from input box using getElementById
            var new_cust_name = document.getElementById("new_customer").value;
            var new_cust_cont = document.getElementById("new_contact_number").value;
            var new_cust_email = document.getElementById("new_email").value;
            var new_cust_gender = document.getElementById("new_gender").value;
            var new_cust_cityname = document.getElementById("new_cityname").value;
            var new_cust_pincode = document.getElementById("new_pincode").value;
            var new_cust_state = document.getElementById("new_state").value;
            var new_cust_contry = document.getElementById("new_contry").value;
    //create json or if we know python that is call dictionary.        
    var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
    //apply stringfy method on json
            data = JSON.stringify(data);
    //insert data into database using javascript ajax
            var send_data = new XMLHttpRequest();
            send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
            send_data.send();

            send_data.onreadystatechange = function(){
              if(send_data.readyState==4 && send_data.status==200){
                alert(send_data.responseText);
              }
            }
          }

django views

    def addNewCustomer(request):
    #if method is get then condition is true and controller check the further line
        if request.method == "GET":
    #this line catch the json from the javascript ajax.
            cust_info = request.GET.get("customerinfo")
    #fill the value in variable which is coming from ajax.
    #it is a json so first we will get the value from using json.loads method.
    #cust_name is a key which is pass by javascript json. 
    #as we know json is a key value pair. the cust_name is a key which pass by javascript json
            cust_name = json.loads(cust_info)['cust_name']
            cust_cont = json.loads(cust_info)['cust_cont']
            cust_email = json.loads(cust_info)['cust_email']
            cust_gender = json.loads(cust_info)['cust_gender']
            cust_cityname = json.loads(cust_info)['cust_cityname']
            cust_pincode = json.loads(cust_info)['cust_pincode']
            cust_state = json.loads(cust_info)['cust_state']
            cust_contry = json.loads(cust_info)['cust_contry']
    #it print the value of cust_name variable on server
            print(cust_name)
            print(cust_cont)
            print(cust_email)
            print(cust_gender)
            print(cust_cityname)
            print(cust_pincode)
            print(cust_state)
            print(cust_contry)
            return HttpResponse("Yes I am reach here.")**

如何搜索和替换文件中的文本?

问题:如何搜索和替换文件中的文本?

如何使用Python 3搜索和替换文件中的文本?

这是我的代码:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

输入文件:

hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd

当我在上面的输入文件中搜索并将“ ram”替换为“ abcd”时,它起了一种魅力。但是,反之亦然,即用“ ram”替换“ abcd”时,一些垃圾字符会保留在末尾。

用“ ram”代替“ abcd”

hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd

How do I search and replace text in a file using Python 3?

Here is my code:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

Input file:

hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd

When I search and replace ‘ram’ by ‘abcd’ in above input file, it works as a charm. But when I do it vice-versa i.e. replacing ‘abcd’ by ‘ram’, some junk characters are left at the end.

Replacing ‘abcd’ by ‘ram’

hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd

回答 0

fileinput已经支持就地编辑。stdout在这种情况下,它将重定向到文件:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

回答 1

正如michaelb958指出的那样,您不能用其他长度的数据替换在原处,因为这会使其余部分无法正确放置。我不同意其他海报,建议您从一个文件中读取并写入另一个文件。相反,我将文件读入内存,修复数据,然后在单独的步骤中将其写出到同一文件中。

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

除非您要处理的海量文件太大而无法一次加载到内存中,否则除非担心在将数据写入文件的第二步过程中该过程中断,否则您可能会担心数据丢失。

As pointed out by michaelb958, you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read from one file and write to another. Instead, I would read the file into memory, fix the data up, and then write it out to the same file in a separate step.

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

Unless you’ve got a massive file to work with which is too big to load into memory in one go, or you are concerned about potential data loss if the process is interrupted during the second step in which you write data to the file.


回答 2

正如杰克·艾德利(Jack Aidley)张贴的文章和JF Sebastian指出的那样,此代码不起作用:

 # Read in the file
filedata = None
with file = open('file.txt', 'r') :
  filedata = file.read()

# Replace the target string
filedata.replace('ram', 'abcd')

# Write the file out again
with file = open('file.txt', 'w') :
  file.write(filedata)`

但是此代码将起作用(我已经对其进行了测试):

f = open(filein,'r')
filedata = f.read()
f.close()

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')
f.write(newdata)
f.close()

使用此方法,filein和fileout可以是同一文件,因为Python 3.3在打开进行写操作时会覆盖该文件。

As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:

 # Read in the file
filedata = None
with file = open('file.txt', 'r') :
  filedata = file.read()

# Replace the target string
filedata.replace('ram', 'abcd')

# Write the file out again
with file = open('file.txt', 'w') :
  file.write(filedata)`

But this code WILL work (I’ve tested it):

f = open(filein,'r')
filedata = f.read()
f.close()

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')
f.write(newdata)
f.close()

Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.


回答 3

你可以这样替换

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()

You can do the replacement like this

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()

回答 4

您也可以使用pathlib

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)

You can also use pathlib.

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)

回答 5

使用单个with块,您可以搜索和替换文本:

with open('file.txt','r+') as f:
    filedata = f.read()
    filedata = filedata.replace('abc','xyz')
    f.truncate(0)
    f.write(filedata)

With a single with block, you can search and replace your text:

with open('file.txt','r+') as f:
    filedata = f.read()
    filedata = filedata.replace('abc','xyz')
    f.truncate(0)
    f.write(filedata)

回答 6

您的问题源于读取和写入同一文件。无需打开fileToSearch进行写入,而是打开实际的临时文件,然后在完成并关闭后tempFile,使用os.rename将新文件移到上方fileToSearch

Your problem stems from reading from and writing to the same file. Rather than opening fileToSearch for writing, open an actual temporary file and then after you’re done and have closed tempFile, use os.rename to move the new file over fileToSearch.


回答 7

(pip install python-util)

from pyutil import filereplace

filereplace("somefile.txt","abcd","ram")

第二个参数(要替换的事物,例如“ abcd”也可以是正则表达式)
将替换所有出现的事件

(pip install python-util)

from pyutil import filereplace

filereplace("somefile.txt","abcd","ram")

The second parameter (the thing to be replaced, e.g. “abcd” can also be a regex)
Will replace all occurences


回答 8

我的变体,在整个文件上一次一个字。

我将其读入内存。

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)

My variant, one word at a time on the entire file.

I read it into memory.

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)

回答 9

我已经做到了:

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")
os.chdir(Dir)

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()

I have done this:

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")
os.chdir(Dir)

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()

回答 10

我稍微修改了Jayram Singh的帖子,以替换每个“!”实例。字符到我想随每个实例增加的数字。认为这对希望修改每行出现多次且要迭代的字符可能会有所帮助。希望能对某人有所帮助。PS-我对编码非常陌生,因此如果我的帖子在任何方面都不适当,我深表歉意,但这对我有用。

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1
        else:
            f2.write(word)
f1.close()
f2.close()

I modified Jayram Singh’s post slightly in order to replace every instance of a ‘!’ character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I’m very new at coding so apologies if my post is inappropriate in any way, but this worked for me.

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1
        else:
            f2.write(word)
f1.close()
f2.close()

回答 11

def word_replace(filename,old,new):
    c=0
    with open(filename,'r+',encoding ='utf-8') as f:
        a=f.read()
        b=a.split()
        for i in range(0,len(b)):
            if b[i]==old:
                c=c+1
        old=old.center(len(old)+2)
        new=new.center(len(new)+2)
        d=a.replace(old,new,c)
        f.truncate(0)
        f.seek(0)
        f.write(d)
    print('All words have been replaced!!!')
def word_replace(filename,old,new):
    c=0
    with open(filename,'r+',encoding ='utf-8') as f:
        a=f.read()
        b=a.split()
        for i in range(0,len(b)):
            if b[i]==old:
                c=c+1
        old=old.center(len(old)+2)
        new=new.center(len(new)+2)
        d=a.replace(old,new,c)
        f.truncate(0)
        f.seek(0)
        f.write(d)
    print('All words have been replaced!!!')

回答 12

像这样:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text = f.read()
    f.write(text.replace(word, replacement))

Like so:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text = f.read()
    f.write(text.replace(word, replacement))

回答 13

def findReplace(find, replace):

    import os 

    src = os.path.join(os.getcwd(), os.pardir) 

    for path, dirs, files in os.walk(os.path.abspath(src)):

        for name in files: 

            if name.endswith('.py'): 

                filepath = os.path.join(path, name)

                with open(filepath) as f: 

                    s = f.read()

                s = s.replace(find, replace) 

                with open(filepath, "w") as f:

                    f.write(s) 
def findReplace(find, replace):

    import os 

    src = os.path.join(os.getcwd(), os.pardir) 

    for path, dirs, files in os.walk(os.path.abspath(src)):

        for name in files: 

            if name.endswith('.py'): 

                filepath = os.path.join(path, name)

                with open(filepath) as f: 

                    s = f.read()

                s = s.replace(find, replace) 

                with open(filepath, "w") as f:

                    f.write(s) 

如何使用类型提示指定多种返回类型

问题:如何使用类型提示指定多种返回类型

我在python中有一个可以返回a bool或a 的函数list。有没有一种方法可以使用类型提示指定返回类型。

例如,这是正确的方法吗?

def foo(id) -> list or bool:
      ...

I have a function in python that can either return a bool or a list. Is there a way to specify the return types using type hints.

For example, Is this the correct way to do it?

def foo(id) -> list or bool:
      ...

回答 0

文档中

typing.Union

联合类型;Union [X,Y]表示X或Y。

因此,表示多个返回数据类型的正确方法是

from typing import Union


def foo(client_id: str) -> Union[list,bool]

但是请注意,不会强制键入。Python仍然是一种动态类型的语言。注释语法已被开发出来,可在代码发布到生产之前的开发过程中提供帮助。如PEP 484所述,“运行时不进行类型检查。”

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

如您所见,我正在传递一个int值并返回一个str。但是,__annotations__将设置为各自的值。

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

请通过PEP 483了解有关类型提示的更多信息。另请参见Python 3.5中的类型提示是什么?

请注意,这仅适用于Python的3.5及以上。PEP 484中明确提到了这一点。

From the documentation

class typing.Union

Union type; Union[X, Y] means either X or Y.

Hence the proper way to represent more than one return data type is

from typing import Union


def foo(client_id: str) -> Union[list,bool]

But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, “no type checking happens at runtime.”

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__ will be set to the respective values.

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?

Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.


回答 1

该语句def foo(client_id: str) -> list or bool:在被求值时等效于 def foo(client_id: str) -> list:并且将不会执行您想要的操作。

描述“ A或B”类型提示的本机方法是Union(由于Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

我不想成为“您为什么仍要这样做”的家伙,但是也许您不想要2种返回类型:

如果要返回布尔值以指示某种特殊的错误情况,请考虑改用Exceptions。如果您要返回布尔值作为某些特殊值,则空列表可能是一个很好的表示。您还可以指出None可以返回Optional[list]

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a “either A or B” type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the “Why do you want to do this anyway” guy, but maybe having 2 return types isn’t what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]


回答 2

如果有人登陆这里搜索“如何指定多个返回值的类型?”,请使用 Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

更多信息:https//code-examples.net/en/q/2651e60

In case anyone landed here in search of “how to specify types of multiple return values?”, use Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

More info: https://code-examples.net/en/q/2651e60


导入错误:没有名为numpy的模块

问题:导入错误:没有名为numpy的模块

我有一个与此问题非常相似的问题,但仍落后了一步。我在Windows 7(对不起)64位系统上仅安装了一个Python 3版本。

我在此链接后安装了numpy- 如问题中所述。安装进行得很好,但是当我执行时

import numpy

我收到以下错误:

导入错误:没有名为numpy的模块

我知道这可能是一个超级基本的问题,但我仍在学习。

谢谢

I have a very similar question to this question, but still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.

I installed numpy following this link – as suggested in the question. The installation went fine but when I execute

import numpy

I got the following error:

Import error: No module named numpy

I know this is probably a super basic question, but I’m still learning.

Thanks


回答 0

NumPy版本1.5.0中添加了对Python 3的支持,因此,首先必须下载/安装较新版本的NumPy。

Support for Python 3 was added in NumPy version 1.5.0, so to begin with, you must download/install a newer version of NumPy.


回答 1

您可以简单地使用

pip install numpy

或者对于python3,使用

pip3 install numpy

You can simply use

pip install numpy

Or for python3, use

pip3 install numpy

回答 2

我认为numpy的安装有问题。这是我解决此问题的步骤。

  1. 请访问此网站以下载正确的软件包:http : //sourceforge.net/projects/numpy/files/
  2. 解压包装
  3. 转到文件
  4. 使用此命令安装numpy: python setup.py install

I think there are something wrong with the installation of numpy. Here are my steps to solve this problem.

  1. go to this website to download correct package: http://sourceforge.net/projects/numpy/files/
  2. unzip the package
  3. go to the document
  4. use this command to install numpy: python setup.py install

回答 3

在Windows上安装Numpy

  1. 以管理员权限打开Windows命令提示符(快速方法:按Windows键。键入“ cmd”。右键单击建议的“命令提示符”,然后选择“以管理员身份运行”)
  2. 使用“ cd”(更改目录)命令导航到Python安装目录的Scripts文件夹。例如“ cd C:\ Program Files(x86)\ PythonXX \ Scripts”

这可能是:C:\ Users \\ AppData \ Local \ Programs \ Python \ PythonXX \ ScriptsC:\ Program Files(x86)\ PythonXX \ Scripts(其中XX代表Python版本号),具体取决于安装位置。使用Windows资源管理器查找文件夹,然后将其从资源管理器地址栏中粘贴或键入地址到命令提示符中,可能会更容易。

  1. 输入以下命令:“ pip install numpy”。

下载并安装软件包后,您应该会看到类似于以下文本的内容。

Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)  
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3

Installing Numpy on Windows

  1. Open Windows command prompt with administrator privileges (quick method: Press the Windows key. Type “cmd”. Right-click on the suggested “Command Prompt” and select “Run as Administrator)
  2. Navigate to the Python installation directory’s Scripts folder using the “cd” (change directory) command. e.g. “cd C:\Program Files (x86)\PythonXX\Scripts”

This might be: C:\Users\\AppData\Local\Programs\Python\PythonXX\Scripts or C:\Program Files (x86)\PythonXX\Scripts (where XX represents the Python version number), depending on where it was installed. It may be easier to find the folder using Windows explorer, and then paste or type the address from the Explorer address bar into the command prompt.

  1. Enter the following command: “pip install numpy”.

You should see something similar to the following text appear as the package is downloaded and installed.

Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)  
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3

回答 4

我也遇到了这个问题(导入错误:没有名为numpy的模块),但就我而言,这是我在Mac OS X中使用PATH变量时遇到的问题。我对.bash_profile文件进行了较早的编辑,该文件导致了Anaconda安装的路径(及其他)不能正确添加。

只要在这里将此注释添加到列表中,以防其他类似我的人以相同的错误消息来到此页面并且遇到与我相同的问题。

I also had this problem (Import Error: No module named numpy) but in my case it was a problem with my PATH variables in Mac OS X. I had made an earlier edit to my .bash_profile file that caused the paths for my Anaconda installation (and others) to not be added properly.

Just adding this comment to the list here in case other people like me come to this page with the same error message and have the same problem as I had.


回答 5

您安装了适用于Python 2.6的Numpy版本-因此您只能将其与Python 2.6一起使用。您必须安装适用于Python 3.x的Numpy,例如:http : //sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python3.2.exe /下载

有关不同版本的概述,请参见此处:http : //sourceforge.net/projects/numpy/files/NumPy/1.6.1/

You installed the Numpy Version for Python 2.6 – so you can only use it with Python 2.6. You have to install Numpy for Python 3.x, e.g. that one: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python3.2.exe/download

For an overview of the different versions, see here: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/


回答 6

安装Numpy后,我也遇到了这个问题。我通过关闭Python解释器并重新打开解决了该问题。如果其他人有此问题,可能要尝试其他方法,也许可以节省几分钟!

I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!


回答 7

面对同样的问题

ImportError: No module named numpy

因此,在我们的情况下(我们使用的是PIP和python 2.7),解决方案是SPLIT pip install命令:

RUN pip install numpy scipy pandas sklearn

RUN pip install numpy scipy
RUN pip install pandas sklearn

在此处找到解决方案:https : //github.com/pandas-dev/pandas/issues/25193,它是pandas的最新更新到v0.24.0

Faced with same issue

ImportError: No module named numpy

So, in our case (we are use PIP and python 2.7) the solution was SPLIT pip install commands :

From

RUN pip install numpy scipy pandas sklearn

TO

RUN pip install numpy scipy
RUN pip install pandas sklearn

Solution found here : https://github.com/pandas-dev/pandas/issues/25193, it’s related latest update of pandas to v0.24.0


回答 8

我通过pip和conda在相同的环境中安装了numpy,仅删除并重新安装其中一个是不够的。

我不得不重新安装两个。

我不知道为什么突然发生,但是解决方案是

pip uninstall numpy

conda uninstall numpy

从康达卸载也删除torchtorchvision

然后

conda install pytorch-cpu torchvision-cpu -c pytorch

pip install numpy

这为我解决了这个问题。

I had numpy installed on the same environment both by pip and by conda, and simply removing and reinstalling either was not enough.

I had to reinstall both.

I don’t know why it suddenly happened, but the solution was

pip uninstall numpy

conda uninstall numpy

uninstalling from conda also removed torch and torchvision.

then

conda install pytorch-cpu torchvision-cpu -c pytorch

and

pip install numpy

this resolved the issue for me.


回答 9

在设置用于机器学习的python时,我也面临着phyton 3的上述问题。

我遵循以下步骤:

安装python-2.7.13.msi

•设置PATH = C:\ Python27

•设置PATH = C:\ Python27 \ Scripts

前往http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

下载的:–numpy-1.13.1 + mkl-cp27-cp27m-win32.whl

          --scipy-0.18.0-cp27-cp27m-win32.whl 

安装numpy:pip install numpy-1.13.1 + mkl-cp27-cp27m-win32.whl

安装scipy:pip install scipy-0.18.0-cp27-cp27m-win32.whl

您可以使用以下cmds测试正确性:-

>>> import numpy
>>> import scipy
>>> import sklearn
>>> numpy.version.version
'1.13.1'
>>> scipy.version.version
'0.19.1'
>>>

I too faced the above problem with phyton 3 while setting up python for machine learning.

I followed the below steps :-

Install python-2.7.13.msi

• set PATH=C:\Python27

• set PATH=C:\Python27\Scripts

Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Downloaded:- — numpy-1.13.1+mkl-cp27-cp27m-win32.whl

          --scipy-0.18.0-cp27-cp27m-win32.whl 

Installing numpy: pip install numpy-1.13.1+mkl-cp27-cp27m-win32.whl

Installing scipy: pip install scipy-0.18.0-cp27-cp27m-win32.whl

You can test the correctness using below cmds:-

>>> import numpy
>>> import scipy
>>> import sklearn
>>> numpy.version.version
'1.13.1'
>>> scipy.version.version
'0.19.1'
>>>

回答 10

我不确定为什么会收到错误消息,但pip3 uninstall numpy随后pip3 install numpy为我解决了该问题。

I’m not sure exactly why I was getting the error, but pip3 uninstall numpy then pip3 install numpy resolved the issue for me.


回答 11

通过Anaconda安装NumPy(使用以下命令):

  • conda安装-c conda-forge numpy
  • conda install -c conda-forge / label /破碎的numpy

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

回答 12

那些正在使用的人会xonshxpip install numpy

Those who are using xonsh, do xpip install numpy.


回答 13

对于使用python 2.7的用户,应尝试:

apt-get install -y python-numpy

而不是pip install numpy

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy


回答 14

你可以试试:

py -3 -m pip安装anyPackageName

在您的情况下使用:

py -3 -m pip安装numpy

谢谢

You can try:

py -3 -m pip install anyPackageName

In your case use:

py -3 -m pip install numpy

Thanks


回答 15

这是numpy版本的问题,请查看$ CAFFE_ROOT / python / requirement.txt。然后执行:sudo apt-get install python-numpy> = xxx,这个问题将会解决。

this is the problem of the numpy’s version, please check out $CAFFE_ROOT/python/requirement.txt. Then exec: sudo apt-get install python-numpy>=x.x.x, this problem will be sloved.


回答 16

import numpy as np
ImportError: No module named numpy 

即使知道安装了numpy并尝试了上述所有建议都没有成功,我还是得到了这个。对我来说,解决方法是删除as np 并直接引用模块。(Centos上的python 3.4.8)。

import numpy
DataTwo=numpy.stack((OutputListUnixTwo))...
import numpy as np
ImportError: No module named numpy 

I got this even though I knew numpy was installed and unsuccessfully tried all the advice above. The fix for me was to remove the as np and directly refer to modules . (python 3.4.8 on Centos) .

import numpy
DataTwo=numpy.stack((OutputListUnixTwo))...

回答 17

您应该尝试使用以下一种安装numpy:

pip install numpy
pip2 install numpy
pip3 install numpy

由于某种原因,在我的情况下,pip2解决了该问题

You should try to install numpy using one of those:

pip install numpy
pip2 install numpy
pip3 install numpy

For some reason in my case pip2 solved the problem


回答 18

在尝试了来自各个站点的许多建议和类似问题之后,对我有用的是卸载所有Python东西并仅重新安装Anaconda(请参阅https://stackoverflow.com/a/38330088/1083292

我以前的Python安装不仅多余,而且还给我带来了麻烦。

After trying many suggestions from various sites and similar questions, what worked for me was to uninstall all Python stuff and reinstall Anaconda only (see https://stackoverflow.com/a/38330088/1083292)

The previous Python installation I had was not only redundant but only caused me trouble.


回答 19

如果在重新安装python之前工作正常,则可以解决此问题。

我只是使用以下方法解决了此问题: 如何使用自制软件在macOS中安装Python 3的早期版本?

If it was working before reinstalling python would solve the issue.

I just hit and resolved this issue using: How can I install a previous version of Python 3 in macOS using homebrew?


回答 20

对我来说,在Windows 10上,我在不知不觉中安装了多个python版本(一个来自PyCharm IDE,另一个来自Windows应用商店)。我从Windows Store卸载了一个,为了更彻底,卸载了numpy pip uninstall numpy,然后再次安装了它pip install numpy。它在PyCharm的终端和命令提示符中都可以使用。

For me, on windows 10, I had unknowingly installed multiple python versions (One from PyCharm IDE and another from Windows store). I uninstalled the one from windows Store and just to be thorough, uninstalled numpy pip uninstall numpy and then installed it again pip install numpy. It worked in the terminal in PyCharm and also in command prompt.