简体   繁体   English

读取文本文件时,为什么在每行前面都出现b'?

[英]When reading a text file, why do I get b' in front of each line?

Not sure what's going on here. 不知道这是怎么回事。 I have a text file with the following contents: 我有一个包含以下内容的文本文件:

1999,3,Rep Armey, Richard K.,[TX-26],0
1999,4,Rep Armey, Richard K.,[TX-26],0
1999,5,Rep Armey, Richard K.,[TX-26],0
1999,6,Rep Hyde, Henry J.,[IL-6],0
1999,7,Rep Talent, Jim,[MO-2],11,Rep DeMint, Jim,[SC-4],...
...

then I read it in using this code in python 3.3: 然后我在python 3.3中使用以下代码阅读了它:

with open(bill_file_name,'rb') as input_file:
    lines=input_file.readlines()

for line in lines:
    line_list=str(line).split(',')
    session=line_list[0]

when I do print(session) I get b'1999 for all of the entries. 当我执行print(session) ,所有条目都得到b'1999

What's going on? 这是怎么回事? How do I avoid this? 如何避免这种情况?

This is probably because you opened the file in binary mode. 这可能是因为您以二进制模式打开了文件。
Try open(bill_file_name,'r') 尝试open(bill_file_name,'r')

That's because you have the b (binary) option enabled while reading. 这是因为您在阅读时启用了b (二进制)选项。 Use the following. 使用以下内容。

with open('a.txt', 'r') as inp:
    lines = inp.readlines()

for line in lines:
    line_list=str(line).split(',')
    session=line_list[0]


>>> print(session)
1999

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在每行的开头都得到b',而在每行的结尾处得到'? - Why do I get b' at the start of each line and ' at the end of each line? 读取文件时,可以使用列表推导获取每个非空白行的顺序位置吗? - Can I use a list comprehension to get a sequential position of each non-blank line when reading in a file? 为什么在将文本写入文件时会得到括号? - Why do I get a parentheses when writing text to a file? 为什么从文本文件中读取时看到“\n”? (Python) - Why do I see '\n' seen when reading from a text file? (python) 如何让 Python 在第一行开始读取文件? - How do I get Python to starting reading a file on the first line? 读取CSV文件时如何从文本字段中删除这些符号? - How do I get rid of these symbols from the text fields when reading a CSV file? 如何将每个文本文件行分成单独的列表? - How do I separate a each text file line into a separate lists? 读取以行号开头的文本文件的每一行 - reading each line of a text file preceded by line numbers 读取混合加密的文本文件时如何添加 b"" - How do I add b" " when reading in text files for Hybrid Encryption 如何摆脱文本文件中每一行前面的“/n”字符? - How can I get rid of the '/n' character in front of every line in a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM