使用python获取数据,目前最主要的方法集中在文本文件,Excel文件,关系型和非关系型数据库,ApI、网页等方面。

一、从文本文件读取运营数据

    1、使用read/readline/readlines读取数据

    python可以读取任意格式的文本数据,使用python读取文本数据的基本步骤是:

    1)定义数据文件     2)获取文件对象    3)读取文件内容    4)关闭文件对象

  (1)定义数据文件

  将数据文件预先复制给一个对象,定义的方法为:

  file_name = [文件名]  

注意文件名可以是本目录下的文件,也可以是相对路径中的文件,也可以是绝对路径中的文件。

  (2)获取文件对象

获取文件对象的意义是基于数据文件产生对象,后续所有相关于这个数据文件的操作都基于该对象产生。语法:

file object = open(name [, mode] [, buffering])

参数:

name 要读取的文件名称或文件变量,必填

mode:打开文件的模式,选填,实际中有:r、r+、w、w+、a、a+。

buffering:文件所需要的缓冲区大小,选填;0:无缓冲,1:线路缓冲。

  (3)读取文件内容

python基于文件对象的读取方法分为三种方法:
方法    描述    返回数据

read    读取文件中的全部数据,直到到达定义的size字节数上限    内容字符串,所有行合并为一个字符串
readline    读取文件中的一行数据,直到到达定义的size字节数上限    内容字符串
readlines    读取文件中的全部数据,直到到达定义的size字节数上限    内容列表,每行数据作为列表中的一个对象

read和readlines是比较常用的方法。

import re

file_name = 'data.txt'
fn = open(file_name)
#read 读取指定长度
line = fn.read(5)
print ("读取的字符串: %s" % (line))
#readline读取一行
line1 = fn.readline()
print("读取的字符串: %s" % (line1))
print('----------------')
#readlines读取文件指针之后的所有数据,内容列表,每行数据作为列表中的一个对象
all_data = fn.readlines()
for single_data in all_data:
  tmp_data = re.split('\t|\n| ',single_data)
  print(tmp_data[0],' ~ ',tmp_data[1])
  print(single_data)
fn.close()

 

  (4)关闭文件对象

每次使用完数据对象后,需要关闭数据对象。语法

文件对象.close()

二、使用Numpy的loadtxt、load、fromfile读取数据

ndarray对象可以保存到磁盘文件并从磁盘文件加载。 可用的 IO 功能有:

load()和save()函数处理 numPy 二进制文件(带npy扩展名)

loadtxt()和savetxt()函数处理正常的文本文件

fromfile()函数读取简单的文本文件数据以及二进制数据。读回数据时需要用户指定元素类型,并对数组的形状进行适当的修改

tofile()将数组中的数据以二进制格式写进文件,写成的文件是fromfile数据的读取来源

实现例子见:

查询loadtxt用法:

# ipython
Python 3.7.2 (default, Feb  6 2020, 13:51:42)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import numpy as np

In [2]: help(np.loadtxt)

loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None)
    Load data from a text file.

Returns    -------
    out : ndarray (N维数组)
        Data read from the text file.

......(其中的参数英文说明也有,自己查阅)

主要几个参数作用:
fname    被读取的文件名(文件的相对地址或者绝对地址)
dtype    指定读取后数据的numpy数据类型 (bool/inti/int8/int16/int32/int64/uint8/....../float16/float32/float64:float/complex64/complex128)
comments    跳过文件中指定参数开头的行(即不读取)
delimiter    指定读取文件中数据的分割符
converters    对读取的数据进行预处理
skiprows    选择跳过的行数
usecols    指定需要读取的列
unpack    选择是否将数据进行向量输出
encoding    对读取的文件进行预编码
代码读取文件内容

import numpy as np

data = np.loadtxt('data.txt', dtype=float, comments='#', delimiter=None, converters=None,skiprows=(1), usecols=(0,1,2,3), unpack=False, ndmin=0)
print(data)

 查询load用法:

In [1]: import numpy as np

In [2]: help(np.load)

Help on function load in module numpy:

load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII')
    Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.

    .. warning:: Loading files that contain object arrays uses the ``pickle``
                 module, which is not secure against erroneous or maliciously
                 constructed data. Consider passing ``allow_pickle=False`` to
                 load data that is known not to contain object arrays for the
                 safer handling of untrusted sources.

    Parameters
    ----------
    file : file-like object, string, or pathlib.Path
        The file to read. File-like objects must support the
        ``seek()`` and ``read()`` methods. Pickled files require that the
        file-like object support the ``readline()`` method as well.
    mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
        If not None, then memory-map the file, using the given mode (see
        `numpy.memmap` for a detailed description of the modes).  A
        memory-mapped array is kept on disk. However, it can be accessed
        and sliced like any ndarray.  Memory mapping is especially useful
        for accessing small fragments of large files without reading the
        entire file into memory.
    allow_pickle : bool, optional
        Allow loading pickled object arrays stored in npy files. Reasons for
        disallowing pickles include security, as loading pickled data can
        execute arbitrary code. If pickles are disallowed, loading object
        arrays will fail. Default: False

        .. versionchanged:: 1.16.3
            Made default False in response to CVE-2019-6446.

    fix_imports : bool, optional
        Only useful when loading Python 2 generated pickled files on Python 3,
        which includes npy/npz files containing object arrays. If `fix_imports`
        is True, pickle will try to map the old Python 2 names to the new names
        used in Python 3.
    encoding : str, optional
        What encoding to use when reading Python 2 strings. Only useful when
        loading Python 2 generated pickled files in Python 3, which includes
        npy/npz files containing object arrays. Values other than 'latin1',
        'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
        data. Default: 'ASCII'

    Returns
    -------
    result : array, tuple, dict, etc.
        Data stored in the file. For ``.npz`` files, the returned instance
        of NpzFile class must be closed to avoid leaking file descriptors.

    Raises
    ------
    IOError
        If the input file does not exist or cannot be read.
    ValueError
        The file contains an object array, but allow_pickle=False given.

    See Also
    --------
    save, savez, savez_compressed, loadtxt
    memmap : Create a memory-map to an array stored in a file on disk.
    lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.

    Notes
    -----
    - If the file contains pickle data, then whatever object is stored
      in the pickle is returned.
    - If the file is a ``.npy`` file, then a single array is returned.
    - If the file is a ``.npz`` file, then a dictionary-like object is
      returned, containing ``{filename: array}`` key-value pairs, one for
      each file in the archive.
    - If the file is a ``.npz`` file, the returned value supports the
      context manager protocol in a similar fashion to the open function::

        with load('foo.npz') as data:
            a = data['a']

      The underlying file descriptor is closed when exiting the 'with'
      block.

考虑传递“allow_pickle=false”来加载已知不包含对象数组的数据,以便更安全地处理不可信的源。以下为代码测试

import numpy as np

write_data = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
np.save('data',write_data)
data = np.load('data.npy',mmap_mode=None, allow_pickle=Flase, fix_imports=True, encoding='ASCII')
print(data)

fromfile的用法:

import numpy as np

help(np.fromfile)

Help on built-in function fromfile in module numpy:

fromfile(...)
    fromfile(file, dtype=float, count=-1, sep='', offset=0)

    Construct an array from data in a text or binary file.

    A highly efficient way of reading binary data with a known data-type,
    as well as parsing simply formatted text files.  Data written using the
    `tofile` method can be read using this function.

    Parameters
    ----------
    file : file or str or Path
        Open file object or filename.

        .. versionchanged:: 1.17.0
            `pathlib.Path` objects are now accepted.

    dtype : data-type
        Data type of the returned array.
        For binary files, it is used to determine the size and byte-order
        of the items in the file.
        Most builtin numeric types are supported and extension types may be supported.

        .. versionadded:: 1.18.0
            Complex dtypes.

    count : int
        Number of items to read. ``-1`` means all items (i.e., the complete
        file).
    sep : str
        Separator between items if file is a text file.(txt文本就是有分隔符)
        Empty ("") separator means the file should be treated as binary.(空为二进制文件)
        Spaces (" ") in the separator match zero or more whitespace characters.(多空格以单空格处理)
        A separator consisting only of spaces must match at least one
        whitespace.(只由空格组成的分隔符必须至少匹配一个空格)
    offset : int
        The offset (in bytes) from the file's current position. Defaults to 0.
        Only permitted for binary files.

        .. versionadded:: 1.17.0

代码例子:

import numpy as np

file_name = 'data.txt'
data = np.loadtxt(file_name, dtype='float', delimiter=' ')
tofile_name = 'binary'
data.tofile(tofile_name) #转成二进制数据文件
fromfile_data = np.fromfile(tofile_name, dtype='float')#读取二进制文件
print(fromfile_data)

二、使用Pandas的read_csv/read_fwf/read_table读取数据

pandas读取文件常用方法:

read_csv 从文件,url,文件型对象中加载带分隔符的数据,主要有csv文件。默认分隔符为逗号
read_table 从文件,url,文件型对象中加载带分隔符的数据。默认分隔符为制表符(“\t”)
read_fwf 读取定宽列格式数据(也就是没有分隔符)或读取表格数据到数据框中
read_cliboard 读取剪切板中的数据,可以看做read_table的剪切板。在将网页转换为表格时很有用
查考文章:
其他的还有:read_excel/read_gbq/read_hdf/read_html/raed_json/read_msgpak/read_pickel/read_sas/read_sql/read_sql_query/read_sql_table/read_sdata,具体的用法可以根据实际需要查询应用。以上方法可以概括了大多数的数据类型读取方法。
 

read_csv的用法:

import pandas as pd
help(pd.read_csv)

Help on function read_csv in module pandas.io.parsers:

read_csv(filepath_or_buffer: Union[str, pathlib.Path, IO[~AnyStr]], sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal: str = '.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True,delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)
    Read a comma-separated values (csv) file into DataFrame.

    Also supports optionally iterating or breaking of the file
    into chunks.

    Additional help can be found in the online docs for
    `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.

    Parameters
    ----------
    filepath_or_buffer : str, path object or file-like object
        Any valid string path is acceptable. The string could be a URL. Valid
        URL schemes include http, ftp, s3, and file. For file URLs, a host is
        expected. A local file could be: file://localhost/path/to/table.csv.

        If you want to pass in a path object, pandas accepts any ``os.PathLike``.

        By file-like object, we refer to objects with a ``read()`` method, such as
        a file handler (e.g. via builtin ``open`` function) or ``StringIO``.
    sep : str, default ','
        Delimiter to use. If sep is None, the C engine cannot automatically detect
        the separator, but the Python parsing engine can, meaning the latter will
        be used and automatically detect the separator by Python's builtin sniffer
        tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
        different from ``'\s+'`` will be interpreted as regular expressions and
        will also force the use of the Python parsing engine. Note that regex
        delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``.
    delimiter : str, default ``None``
        Alias for sep.
    header : int, list of int, default 'infer'
        Row number(s) to use as the column names, and the start of the
        data.  Default behavior is to infer the column names: if no names
        are passed the behavior is identical to ``header=0`` and column
        names are inferred from the first line of the file, if column
        names are passed explicitly then the behavior is identical to
        ``header=None``. Explicitly pass ``header=0`` to be able to
        replace existing names. The header can be a list of integers that
        specify row locations for a multi-index on the columns
        e.g. [0,1,3]. Intervening rows that are not specified will be
        skipped (e.g. 2 in this example is skipped). Note that this
        parameter ignores commented lines and empty lines if
        ``skip_blank_lines=True``, so ``header=0`` denotes the first line of
        data rather than the first line of the file.
    names : array-like, optional
        List of column names to use. If the file contains a header row,
        then you should explicitly pass ``header=0`` to override the column names.
        Duplicates in this list are not allowed.
    index_col : int, str, sequence of int / str, or False, default ``None``
      Column(s) to use as the row labels of the ``DataFrame``, either given as
      string name or column index. If a sequence of int / str is given, a
      MultiIndex is used.

      Note: ``index_col=False`` can be used to force pandas to *not* use the first
      column as the index, e.g. when you have a malformed file with delimiters at
      the end of each line.
    usecols : list-like or callable, optional
        Return a subset of the columns. If list-like, all elements must either
        be positional (i.e. integer indices into the document columns) or strings
        that correspond to column names provided either by the user in `names` or
        inferred from the document header row(s). For example, a valid list-like
        `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
        Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
        To instantiate a DataFrame from ``data`` with element order preserved use
        ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
        in ``['foo', 'bar']`` order or
        ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
        for ``['bar', 'foo']`` order.

        If callable, the callable function will be evaluated against the column
        names, returning names where the callable function evaluates to True. An
        example of a valid callable argument would be ``lambda x: x.upper() in
        ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster
        parsing time and lower memory usage.
    squeeze : bool, default False
        If the parsed data only contains one column then return a Series.
    prefix : str, optional
        Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...
    mangle_dupe_cols : bool, default True
        Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than
        'X'...'X'. Passing in False will cause data to be overwritten if there
        are duplicate names in the columns.
    dtype : Type name or dict of column -> type, optional
        Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32,
        'c': 'Int64'}
        Use `str` or `object` together with suitable `na_values` settings
        to preserve and not interpret dtype.
        If converters are specified, they will be applied INSTEAD
        of dtype conversion.
    engine : {'c', 'python'}, optional
        Parser engine to use. The C engine is faster while the python engine is
        currently more feature-complete.
    converters : dict, optional
        Dict of functions for converting values in certain columns. Keys can either
        be integers or column labels.
    true_values : list, optional
        Values to consider as True.
    false_values : list, optional
        Values to consider as False.
    skipinitialspace : bool, default False
        Skip spaces after delimiter.
    skiprows : list-like, int or callable, optional
        Line numbers to skip (0-indexed) or number of lines to skip (int)
        at the start of the file.

        If callable, the callable function will be evaluated against the row
        indices, returning True if the row should be skipped and False otherwise.
        An example of a valid callable argument would be ``lambda x: x in [0, 2]``.
    skipfooter : int, default 0
        Number of lines at bottom of file to skip (Unsupported with engine='c').
    nrows : int, optional
        Number of rows of file to read. Useful for reading pieces of large files.
    na_values : scalar, str, list-like, or dict, optional
        Additional strings to recognize as NA/NaN. If dict passed, specific
        per-column NA values.  By default the following values are interpreted as
        NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
        '1.#IND', '1.#QNAN', '<NA>', 'N/A', 'NA', 'NULL', 'NaN', 'n/a',
        'nan', 'null'.
    keep_default_na : bool, default True
        Whether or not to include the default NaN values when parsing the data.
        Depending on whether `na_values` is passed in, the behavior is as follows:

        * If `keep_default_na` is True, and `na_values` are specified, `na_values`
          is appended to the default NaN values used for parsing.
        * If `keep_default_na` is True, and `na_values` are not specified, only
          the default NaN values are used for parsing.
        * If `keep_default_na` is False, and `na_values` are specified, only
          the NaN values specified `na_values` are used for parsing.
        * If `keep_default_na` is False, and `na_values` are not specified, no
          strings will be parsed as NaN.

        Note that if `na_filter` is passed in as False, the `keep_default_na` and
        `na_values` parameters will be ignored.
    na_filter : bool, default True
        Detect missing value markers (empty strings and the value of na_values). In
        data without any NAs, passing na_filter=False can improve the performance
        of reading a large file.
    verbose : bool, default False
        Indicate number of NA values placed in non-numeric columns.
    skip_blank_lines : bool, default True
        If True, skip over blank lines rather than interpreting as NaN values.
    parse_dates : bool or list of int or names or list of lists or dict, default False
        The behavior is as follows:

        * boolean. If True -> try parsing the index.
        * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
          each as a separate date column.
        * list of lists. e.g.  If [[1, 3]] -> combine columns 1 and 3 and parse as
          a single date column.
        * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call
          result 'foo'

        If a column or index cannot be represented as an array of datetimes,
        say because of an unparseable value or a mixture of timezones, the column
        or index will be returned unaltered as an object data type. For
        non-standard datetime parsing, use ``pd.to_datetime`` after
        ``pd.read_csv``. To parse an index or column with a mixture of timezones,
        specify ``date_parser`` to be a partially-applied
        :func:`pandas.to_datetime` with ``utc=True``. See
        :ref:`io.csv.mixed_timezones` for more.

        Note: A fast-path exists for iso8601-formatted dates.
    infer_datetime_format : bool, default False
        If True and `parse_dates` is enabled, pandas will attempt to infer the
        format of the datetime strings in the columns, and if it can be inferred,
        switch to a faster method of parsing them. In some cases this can increase
        the parsing speed by 5-10x.
    keep_date_col : bool, default False
        If True and `parse_dates` specifies combining multiple columns then
        keep the original columns.
    date_parser : function, optional
        Function to use for converting a sequence of string columns to an array of
        datetime instances. The default uses ``dateutil.parser.parser`` to do the
        conversion. Pandas will try to call `date_parser` in three different ways,
        advancing to the next if an exception occurs: 1) Pass one or more arrays
        (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the
        string values from the columns defined by `parse_dates` into a single array
        and pass that; and 3) call `date_parser` once for each row using one or
        more strings (corresponding to the columns defined by `parse_dates`) as
        arguments.
    dayfirst : bool, default False
        DD/MM format dates, international and European format.
    cache_dates : bool, default True
        If True, use a cache of unique, converted dates to apply the datetime
        conversion. May produce significant speed-up when parsing duplicate
        date strings, especially ones with timezone offsets.

        .. versionadded:: 0.25.0
    iterator : bool, default False
        Return TextFileReader object for iteration or getting chunks with
        ``get_chunk()``.
    chunksize : int, optional
        Return TextFileReader object for iteration.
        See the `IO Tools docs
        <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_
        for more information on ``iterator`` and ``chunksize``.
    compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
        For on-the-fly decompression of on-disk data. If 'infer' and
        `filepath_or_buffer` is path-like, then detect compression from the
        following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no
        decompression). If using 'zip', the ZIP file must contain only one data
        file to be read in. Set to None for no decompression.
    thousands : str, optional
        Thousands separator.
    decimal : str, default '.'
        Character to recognize as decimal point (e.g. use ',' for European data).
    lineterminator : str (length 1), optional
        Character to break file into lines. Only valid with C parser.
    quotechar : str (length 1), optional
        The character used to denote the start and end of a quoted item. Quoted
        items can include the delimiter and it will be ignored.
    quoting : int or csv.QUOTE_* instance, default 0
        Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
        QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
    doublequote : bool, default ``True``
       When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
       whether or not to interpret two consecutive quotechar elements INSIDE a
       field as a single ``quotechar`` element.
    escapechar : str (length 1), optional
        One-character string used to escape other characters.
    comment : str, optional
        Indicates remainder of line should not be parsed. If found at the beginning
        of a line, the line will be ignored altogether. This parameter must be a
        single character. Like empty lines (as long as ``skip_blank_lines=True``),
        fully commented lines are ignored by the parameter `header` but not by
        `skiprows`. For example, if ``comment='#'``, parsing
        ``#empty\na,b,c\n1,2,3`` with ``header=0`` will result in 'a,b,c' being
        treated as the header.
    encoding : str, optional
        Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
        standard encodings
        <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .
    dialect : str or csv.Dialect, optional
        If provided, this parameter will override values (default or not) for the
        following parameters: `delimiter`, `doublequote`, `escapechar`,
        `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to
        override values, a ParserWarning will be issued. See csv.Dialect
        documentation for more details.
    error_bad_lines : bool, default True
        Lines with too many fields (e.g. a csv line with too many commas) will by
        default cause an exception to be raised, and no DataFrame will be returned.
        If False, then these "bad lines" will dropped from the DataFrame that is
        returned.
    warn_bad_lines : bool, default True
        If error_bad_lines is False, and warn_bad_lines is True, a warning for each
        "bad line" will be output.
    delim_whitespace : bool, default False
        Specifies whether or not whitespace (e.g. ``' '`` or ``'    '``) will be
        used as the sep. Equivalent to setting ``sep='\s+'``. If this option
        is set to True, nothing should be passed in for the ``delimiter``
        parameter.
    low_memory : bool, default True
        Internally process the file in chunks, resulting in lower memory use
        while parsing, but possibly mixed type inference.  To ensure no mixed
        types either set False, or specify the type with the `dtype` parameter.
        Note that the entire file is read into a single DataFrame regardless,
        use the `chunksize` or `iterator` parameter to return the data in chunks.
        (Only valid with C parser).
    memory_map : bool, default False
        If a filepath is provided for `filepath_or_buffer`, map the file object
        directly onto memory and access the data directly from there. Using this
        option can improve performance because there is no longer any I/O overhead.
    float_precision : str, optional
        Specifies which converter the C engine should use for floating-point
        values. The options are `None` for the ordinary converter,
        `high` for the high-precision converter, and `round_trip` for the
        round-trip converter.

    Returns
    -------
    DataFrame or TextParser
        A comma-separated values (csv) file is returned as two-dimensional
        data structure with labeled axes.

参数太多,主要的几个参数为:
filepath_or_buffer:字符串,要读取的文件对象,必填
sep:字符串,分隔符号,选填,默认为英文','
names:类数组,列名,选填,默认为空
skiprows:类字典或整数型,要跳过的行或行数,选填,默认为空
nrows:整数型,要读取的前记录总数,选填,默认为空,常用来在大型数据集下做初步探索用
thousands:字符串,千位符符号,选点,默认为空,因为欧洲的千位符和小数点与中国的刚好相反。
decimal:字符串,小数点符号,选填,默认为(.)
返回:DataFrame 或 TextParser

例子:

import pandas as pd

csv_data = pd.read_csv('staff_emp.csv',sep=',',delimiter=None, header='infer', names=['col1','col2','col3','col4','col5'],index_col=None,usecols=None,skiprows=None)
print(csv_data)

read_fwf的方法说明:读取表格或固定宽度格式的文本行到数据框。
参数和read_csv一样多,并且大多都一样用法。仅说一个特有的参数:
widths:由整数组成的列表,选填,如果间隔符是连续的,可以使用的字段宽度列表。而不是colspecs。

例子:
 

import pandas as pd

fwf_data = pd.read_fwf('data1.txt',sep='\t',widths=[4,4,4,4,4],names=['col1','col2','col3','col4','col5'])
print(fwf_data)

read_table 方法读取数据: 读取通用分隔符的数据文件到数据框,用法:
read_table(filepath_or_buffer: Union[str, pathlib.Path, IO[~AnyStr]], sep='\t', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False,cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal: str = '.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)
参数有点多,和read_csv一模一样,自行查询吧。。(help(pandas.read_table))

例子:
 

import pandas as pd

table_data = pd.read_table('data2.txt', sep='\t', names=['col1','col2','col3','col4','col5'],delimiter=None,header='infer',index_col=None,usecols=None)
print(table_data)

其他例子:
读取xlsx文件:

import pandas as pd

excel_file = 'data.xlsx'
excel_data = pd.read_excel(excel_file,sheet_name=0,header=None,names=None,index_col=None,usecols=None)
print(excel_data)

sql获取信息,生成文件:

import pymysql
import pandas as pd

con = pymysql.connect(host="127.0.0.1",user="root",password="123456",db="testdb")
# 读取sql
data_sql=pd.read_sql("select * from staff_emp",con)
# 存储
data_sql.to_csv("test.csv")

xlrd库处理xlsx文件信息:

import xlrd

xlsx = xlrd.open_workbook('data.xlsx')
print('all sheets:%s' % xlsx.sheet_names())
print('==================================')

sheet1 = xlsx.sheets()[0]   #第一张sheet
sheet1_name = sheet1.name   #名称
sheet1_cols = sheet1.ncols  #列数
sheet1_nrows = sheet1.nrows #行数

print(('sheet1 name:%s \nSheet1 cols: %s \nsheet1 rows: %s') % (sheet1_name,sheet1_cols,sheet1_nrows))
print('==================================')

sheet1_nrows4 = sheet1.row_values(4)
sheet1_cols2 = sheet1.col_values(2)  #第二列数据
cell123 = sheet1.row(2)[3].value #第三行第四列数据

print(('row 4: %s\ncol 2: %s\ncell 1: %s\n') % (sheet1_nrows4, sheet1_cols2, cell123))
print('==================================')
for i in range(sheet1_nrows):
        print(sheet1.row_values(i))

用connector来打开数据库连接(mysql):
 

import mysql.connector

config = {'host':'127.0.0.1',
        'user':'root',
        'password':'123456',
        'port':3306,
        'database':'testdb',
        'charset':'gb2312'
        }

conn = mysql.connector.connect(**config)
cursor = conn.cursor()
sql = "select * from staff_emp"
cursor.execute(sql)
data = cursor.fetchall()
for i in data[:13]:
        print(i)
cursor.close()
conn.close()

完成测试实验