原始代码:

    1. file = open(r'C:\Users\pi\Desktop\2.txt')
    2. d = loadtxt(file, dtype=str)
    3. print(d[0])
    4. ["b'love'" "b'byte'" "b'you'"]
    5. file = open(r'C:\Users\pi\Desktop\2.txt', 'rb')
    6. d = loadtxt(file, dtype=str)
    7. print(d)
    8. ["b'love'" "b'byte'" "b'you'"]
    9. file = open(r'C:\Users\pi\Desktop\2.txt', 'r', encoding='utf-8')
    10. d = loadtxt(file, dtype=str)
    11. print(d)
    12. ["b'love'" "b'byte'" "b'you'"]

    输出的值前面总会在字符串前面加上“b”,原因是np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2. But Python 3 uses unicode, and marks bytestrings with this b. numpy.loadtxt中也声明了:Note that generators should return byte strings for Python 3k.

    如何去除这个“b”,只需使用下面这个代码:

    1. np.loadtxt(filename, dtype=bytes).astype(str)

    作者:Cameron
    链接:https://www.zhihu.com/question/28690341/answer/164344688
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。