繁体   English   中英

从csv读取时仅在第一个值中无法解释的前导空间

[英]Unexplainable leading space only in first value when reading from csv

我正在从.csv中读取某些值,并且由于某些原因,在第一个值的开头添加了空格。 有谁知道为什么会这样吗?

输入:

在此处输入图片说明

    with open('input.csv') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:

        host = row[0]
        destination = row[1]
        port = row[2]
        print("HOST")
        print(host)

输出:

在此处输入图片说明

请注意,input.csv在第一个值的开头没有任何空格。 同样使用lstrip()似乎无法解决此问题。

试试看

with open('input.csv') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:

    host = row[0]
    host = host.strip() #  choo off whitespace
    destination = row[1]
    port = row[2]
    print("HOST")
    print(host)

并排注意:

csv_reader = csv.reader(csv_file, skipinitialspace=True)

skipinitialspace:如果设置为True,则分隔符之后的任何空白都将被忽略。

它可能是零宽度无中断空间(U + FEFF)代码点,并且用作UTF16和UTF32编码文件的字节顺序标记(BOM),以及UTF-8编码文件的签名。 它不会被.strip()删除。 假设您的.CSV以UTF-8编码,则使用open('input.csv',encoding='utf-8-sig')删除签名(如果存在open('input.csv',encoding='utf-8-sig') 其他选项是utf16utf32 他们需要BOM并也将其删除,但很可能是UTF-8。

使用print(ascii(host))来查看字符实际是什么:

>>> host = '\ufeffBob'
>>> print(x)
 Bob
>>> print(ascii(x))
'\ufeffBob'
 with open('input.csv') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:

        host = row[0]
        destination = row[1]
        port = row[2]
        print("HOST")
        print(host) #  Remove spaces by treating strings
        print(host.strip()) # Default is a blank character

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM