Category Archives: Python

Python AttributeError: ‘unicode’ object has no attribute ‘tzinfo’

Internal Server Error: /demo/machineinfo.html
Traceback (most recent call last):
File “C:\Python27\lib\site-packages\django\core\handlers\exception.py”, line 41, in inner
response = get_response(request)
File “C:\Python27\lib\site-packages\django\core\handlers\base.py”, line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File “C:\Python27\lib\site-packages\django\core\handlers\base.py”, line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File “G:\python\project\myApp\machineviews.py”, line 25, in htmlmachineinfo
print machineinfo.objects.filter(serialNumber=machineser)
File “C:\Python27\lib\site-packages\django\db\models\query.py”, line 226, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File “C:\Python27\lib\site-packages\django\db\models\query.py”, line 250, in __iter__
self._fetch_all()
File “C:\Python27\lib\site-packages\django\db\models\query.py”, line 1118, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File “C:\Python27\lib\site-packages\django\db\models\query.py”, line 62, in __iter__
for row in compiler.results_iter(results):
File “C:\Python27\lib\site-packages\django\db\models\sql\compiler.py”, line 842, in results_iter
row = self.apply_converters(row, converters)
File “C:\Python27\lib\site-packages\django\db\models\sql\compiler.py”, line 827, in apply_converters
value = converter(value, expression, self.connection, self.query.context)
File “C:\Python27\lib\site-packages\django\db\backends\mysql\operations.py”, line 239, in convert_datetimefield_value
value = timezone.make_aware(value, self.connection.timezone)
File “C:\Python27\lib\site-packages\django\utils\timezone.py”, line 285, in make_aware
return timezone.localize(value, is_dst=is_dst)
File “C:\Python27\lib\site-packages\pytz\__init__.py”, line 222, in localize
if dt.tzinfo is not None:
AttributeError: ‘unicode’ object has no attribute ‘tzinfo’

The temporary solution takes the database

models.DateTimeField(auto_now_add=True)
The relevant time statement is commented out first, and then executed.
I'll update it later when I have a solution.

[Django] python manage.py syncdb Unknown command: ‘syncdb’

In the version after Django 1.9, the python manage.py syncdb command is modified to Python manage.py migrate, which runs normally

Select SQLite visual SQLite studio-3.1.1 to operate the database

Synchronization command:

commands are
python manage.py makemigrations
python manage.py migrate

Django 1.9 background becomes Chinese

In version 1.9, the simplified Chinese code is zh_ Hans, the traditional Chinese code is zh_ Hant。

Modify as follows:
simplified Chinese:
Modify language_ The code parameter is set to “zh Hans”

LANGUAGE_CODE = ‘zh-Hans’

Or
traditional Chinese:
Modify language_ The code parameter is set to “zh hant”

LANGUAGE_CODE = ‘zh_Hant’

The Usage of Numpy.unravel_index() function

numpy.unravel_ The index () function is used to get the position of an index value of type/group int in a multidimensional array

Grammar:

numpy.unravel_ index(indices, dims)

Take a simple example

Find the index of the largest element of a multidimensional array

A = np.random.randint(1,100,size=(2,3,5))
print(A)
array([[[98, 29, 32, 73, 90],
        [36, 52, 24,  2, 37],
        [66, 80, 23, 29, 98]],

       [[17, 32, 58, 99, 74],
        [53,  3, 20, 48, 28],
        [53,  7, 74, 34, 68]]])

ind_max = np.argmax(A)
print(ind_max)
18


ind_max_src = np.unravel_index(ind_max, A.shape)
print(ind_max_src)
(1, 0, 3)

print(A[ind_max_src])
99

If NP. Unreavel_ The first parameter of index (indexes, DIMS) is an array of int type

Returns the index of the original array corresponding to each element in the array (i.e. the value of the flattern index)

idx = np.unravel_index((0,29),A.shape) 
print(idx)
# (array([0, 1], dtype=int64), array([0, 2], dtype=int64), array([0, 4], dtype=int64))

print(idx[0])
print(idx[1])
print(idx[2])
[0 1]
[0 2]
[0 4]

first_idx = (idx[0][0],idx[1][0],idx[2][0])
print(first_idx)
print(A[first_idx])
(0, 0, 0)
98

Mac version PIP install — upgrade PIP update version error

Error Message:

➜ ~ sudo pip install –upgrade pip

Collecting pip
Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB)
74% |███████████████████████▊ | 888kB 21kB/s eta 0:00:15Exception:
Traceback (most recent call last):
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py”, line 223, in main
status = self.run(options, args)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py”, line 282, in run
requirement_set.prepare_files(finder)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py”, line 334, in prepare_files
functools.partial(self._prepare_file, finder))
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py”, line 321, in _walk_req_to_install
more_reqs = handler(req_to_install)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py”, line 491, in _prepare_file
session=self.session)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/download.py”, line 825, in unpack_url
session,
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/download.py”, line 673, in unpack_http_url
from_path, content_type = _download_http_url(link, session, temp_dir)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/download.py”, line 886, in _download_http_url
_download_url(resp, link, content_file)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/download.py”, line 621, in _download_url
for chunk in progress_indicator(resp_read(4096), 4096):
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/ui.py”, line 133, in iter
for x in it:
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/download.py”, line 586, in resp_read
decode_content=False):
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py”, line 307, in stream
data = self.read(amt=amt, decode_content=decode_content)
File “/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py”, line 267, in read
raise ReadTimeoutError(self._pool, None, ‘Read timed out.’)
ReadTimeoutError: HTTPSConnectionPool(host=’pypi.python.org’, port=443): Read timed out.

Solution: sudo pip install –index https://pypi.mirrors.ustc.edu.cn/simple/ –upgrade pip

MySQLdb-python Install Error

➜ ~ pip install MySQL-python
Collecting MySQL-python
Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File “<string>”, line 1, in <module>
File “/private/var/folders/rj/lcp0d7815kl2v5xh0j4zm6h00000gn/T/pip-build-tD7Et4/MySQL-python/setup.py”, line 17, in <module>
metadata, options = get_config()
File “setup_posix.py”, line 43, in get_config
libs = mysql_config(“libs_r”)
File “setup_posix.py”, line 25, in mysql_config
raise EnvironmentError(“%s not found” % (mysql_config.path,))
EnvironmentError: mysql_config not found

—————————————-
Command “python setup.py egg_info” failed with error code 1 in /private/var/folders/rj/lcp0d7815kl2v5xh0j4zm6h00000gn/T/pip-build-tD7Et4/MySQL-python/

Solution: brew install mysql

sudo pip install MySQL-python

You-get Warning urllib.error.URLError:

The error is as follows:

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

All error messages are as follows:

sudo you-get --debug https://www.youtube.com/watch?v=1234567890a

[DEBUG] get_content: https://www.youtube.com/get_video_info?video_id=1234567890a&eurl=https%3A%2F%2Fy
you-get: version 0.4.1410, a tiny downloader that scrapes the web.
you-get: Namespace(URL=['https://www.youtube.com/watch?v=1234567890a'], auto_rename=False, cookies=None, debug=True, extractor_proxy=None, force=False, format=None, help=False, http_proxy=None, info=False, input_file=None, insecure=False, itag=None, json=False, no_caption=False, no_merge=False, no_proxy=False, output_dir='.', output_filename=None, password=None, player=None, playlist=False, skip_existing_file_size_check=False, socks_proxy=None, stream=None, timeout=600, url=False, version=False)

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1317, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1230, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1276, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1225, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1004, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 944, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect
    self.sock = self._context.wrap_socket(self.sock,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/bin/you-get", line 10, in <module>
    sys.exit(main())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/__main__.py", line 92, in main
    main(**kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 1766, in main
    script_main(any_download, any_download_playlist, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 1648, in script_main
    download_main(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 1310, in download_main
    download(url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 1757, in any_download
    m.download(url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/extractor.py", line 48, in download_by_url
    self.prepare(**kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/extractors/youtube.py", line 205, in prepare
    video_info = parse.parse_qs(get_content('https://www.youtube.com/get_video_info?video_id={}&eurl=https%3A%2F%2Fy'.format(self.vid)))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 442, in get_content
    response = urlopen_with_retry(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/you_get/common.py", line 411, in urlopen_with_retry
    return request.urlopen(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 542, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1360, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

Solution: run the following command to install the certificate

/Applications/Python\ 3.8/Install\ Certificates.command

 

Differences of urllib, urllib2, httplib and httplib2 libraries in Python

if you only use python3. X, you can not read it now, just remember to have a urllib library for example

Python 2. X has these library names: urllib, urllib2, urllib3, httplib, httplib2, requests

Python 3. X has these library names: urllib, urllib3, httplib2, requests

Both of them have urllib3 and requests, which are not standard libraries. Urllib3 provides thread safe connection pool and file post support, which has little to do with urllib and urllib2. Requests call themselves HTTP for humans, which is more concise and convenient to use

for python2. X:

The main differences between urllib and urllib2 are as follows:

Urllib2 can accept request object, set header information for URL, modify user agent, set cookie, etc. urllib2 can only accept a common URL

Urllib provides some primitive methods, but urllib2 doesn’t, such as URLEncode

Some examples of official documents of urllib

Using the GET method with parameters to retrieve the URL
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read()
Using the POST method
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
Use HTTP proxy, automatic tracking redirection
>>> import urllib
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.FancyURLopener(proxies)
>>> f = opener.open("http://www.python.org")
>>> f.read()
Not using a proxy
>>> import urllib
>>> opener = urllib.FancyURLopener({})
>>> f = opener.open("http://www.python.org/")
>>> f.read()

Examples of several official documents of urllib2:

GET the next URL
>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read()

Use basic HTTP authentication
import urllib2
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
build_opener() Many handlers are provided by default, including proxy handlers, which are set by default to those provided by environment variables.

An example of using a proxy
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.example.com/login.html')

Add HTTP request headers
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib2.urlopen(req)

更改User-agent
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')

**Httplib and httplib2 * * httplib is the implementation of HTTP client protocol, which is usually not used directly. Urllib is based on httplib. Httplib2 is a third-party library, which has more features than httplib

for python3. X:

Here, urllib becomes a package, which is divided into several modules

urllib.request Used to open and read URLs, 
urllib.error is used to handle exceptions caused by the previous request, 
urllib.parse is used to parse URLs, 
urllib.robotparser for parsing robots.txt files

Urllib. Urlopen() in python2. X is abandoned, and urllib2. Urlopen() is equivalent to urllib. Request. Urlopen() in python3. X

A few official examples:

GET一个URL
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))

PUT a request
import urllib.request
DATA=b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
with urllib.request.urlopen(req) as f:
    pass
print(f.status)
print(f.reason)

Basic HTTP authentication
import urllib.request
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

use proxy
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.example.com/login.html')

add header
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib.request.urlopen(req)

change User-agent
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')

Setting the parameters of the URL when using GET
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
...     print(f.read().decode('utf-8'))
...

Set parameters when using POST
>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
...     print(f.read().decode('utf-8'))
...

proxy
>>> import urllib.request
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> with opener.open("http://www.python.org") as f:
...     f.read().decode('utf-8')
...
Do not use a proxy, override the proxy of the environment variable
>>> import urllib.request
>>> opener = urllib.request.FancyURLopener({})
>>> with opener.open("http://www.python.org/") as f:
...     f.read().decode('utf-8')
...

 

Python crawling picture prompt urllib.error.httperror: http error 403: forbidden solution

Recently a Traceback (most recent call last) was thrown when using python to crawl to the girl’s picture:
File “meinv.py”, line 108, in <module>
main()
File “meinv.py”, line 104, in main
imghandle.run()
File “meinv.py”, line 96, in run
self.handle_data(response)
File “meinv.py”, line 84, in handle_data
self.handle_imgdata(res, iname)
File “meinv.py”, line 65, in handle_imgdata
urllib.request.urlretrieve(imgurl, filepath)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 188, in urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 163, in urlopen
return opener.open(url, data, timeout)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 472, in open
response = meth(req, response)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 582, in http_response
‘http’, request, response, code, msg, hdrs)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 510, in error
return self._call_chain(*args)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 444, in _call_chain
result = func(*args)
File “D:\allkitinstall\python3.5.3\lib\urllib\request.py”, line 590, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden error

Let’s start by posting the code.

This is the function that constructs the request object

Here is the code that sends the request and downloads the image

Checked a lot of information on the Internet, said that the lack of user-agent header, but I have obviously added, tried many times or did not work, just when I was about to give up, in the packet capture tool suddenly found a picture request header in the header information Referer, which suddenly remembered

Many sites will set the Referer header to do anti-theft chain function, to prevent the site was malicious requests, so I was happy to add this request header

Try again

Done!

 

Python 3: URLEncode and urlcode

Abstract:There is a need for urlencode and urldecode in the process of code, next, how to urlencode and urldecode in python3

Function

urlencode:

urllib.parse.quote(string, safe=’/’, encoding=None, errors=None)

urldecode:

urllib.parse.unquote(string, encoding=’utf-8′, errors=’replace’)

Example

    

import urllib.parse

test = "hello world"
print (test)
# urlencode
test01 = urllib.parse.quote(test)
print(test)
#urldecode
print(urllib.parse.unquote(new))

Python OpenCV Save Image error: (-215:Assertion failed) !_img.empty()

Detailed description of the error

When using the imwrite function of OpenCV to save pictures, report CV2. Error: opencv (4.2.0) C:: <projects/opencv Python/opencv/modules/imgcodecs/SRC/loadsave cpp:715 : error: (-215:Assertion failed) !_ img.empty() in function ‘cv::imwrite’

Error analysis

Use clip to segment the image. The code is as follows

clip_img = img[top:(top+height),left:(left+width),:]

terms of settlement

img is not none , through clip_ IMG is none can’t be judged. It can be judged by size attribute. The code is as follows

if clip_img.size ==  0:#Do not use imwriter for this case

In addition to not processing, there is another solution, check whether the values of the divided rows and columns are legal , legal conditions:

The minimum value of segmentation cannot be less than 0, the maximum value of segmentation cannot be greater than the width and height of the picture, and the maximum value of segmentation must be greater than the minimum value of segmentation

Python: How to Read file initialization from file failed by panda

Pandas reports the following error when reading the file:

--------------------------------------------------------------------------
OSError                                  Traceback (most recent call last)
<ipython-input-21-f8680ec116e3> in <module>()
      1 #f = open(path)
----> 2 res = pd.read_csv('myfile.csv')

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    644                     skip_blank_lines=skip_blank_lines)
    645 
--> 646         return _read(filepath_or_buffer, kwds)
    647 
    648     parser_f.__name__ = name

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    387 
    388     # Create the parser.
--> 389     parser = TextFileReader(filepath_or_buffer, **kwds)
    390 
    391     if (nrows is not None) and (chunksize is not None):

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds)
    728             self.options['has_index_names'] = kwds['has_index_names']
    729 
--> 730         self._make_engine(self.engine)
    731 
    732     def close(self):

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine)
    921     def _make_engine(self, engine='c'):
    922         if engine == 'c':
--> 923             self._engine = CParserWrapper(self.f, **self.options)
    924         else:
    925             if engine == 'python':

E:\anaconda_python\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds)
   1388         kwds['allow_leading_cols'] = self.index_col is not False
   1389 
-> 1390         self._reader = _parser.TextReader(src, **kwds)
   1391 
   1392         # XXX

pandas\parser.pyx in pandas.parser.TextReader.__cinit__ (pandas\parser.c:4184)()

pandas\parser.pyx in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:8471)()

OSError: Initializing from file failed

When you use panda to read a file and report this error, it is usually because your file name contains Chinese, for example:

res = pd.read_csv('myfile.csv')

In this case, an error will be reported

f = open('myfile.csv')
res = pd.read_csv(f)

Then you can read the file