[英]Unexplainable leading space only in first value when reading from csv
试试看
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')
。 其他选项是utf16
和utf32
。 他们需要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.