[英]python rstrip usage within loop while reading csv file
I have a CSV file where I am looping and matching with my database for getting results according to these matches. 我有一个CSV文件,我在其中循环并与数据库匹配以根据这些匹配获取结果。
I encountered a problem in the case where there is a space at the end of the text. 在文本末尾有空格的情况下,我遇到了一个问题。 So I did my research and found that I need to add the
rstrip
function to remove spaces at the end of the text. 因此,我进行了研究,发现需要添加
rstrip
函数以删除文本末尾的空格。
Here is my code: 这是我的代码:
with open(path, encoding='utf-8') as f:
data = csv.reader(f, delimiter='|')
for row in data:
line = row[0]
cleanline = line.rstrip()
lines.append(cleanline)
query = line
The code is not working. 该代码不起作用。 I tried also strings like
/s
or strip
, and replace functions as well but nothing is working. 我也尝试了
/s
或strip
类/s
字符串,并替换了函数,但没有任何效果。 What can be the reason? 可能是什么原因? What am I doing wrong?
我究竟做错了什么?
CSV File with empty space at the end: CSV文件末尾有空白:
Sistem en az 23.8 inç boyutlarında olmalıdır.
1 adet HDMI port olmalıdır.
You could try the following approach: 您可以尝试以下方法:
import csv
path = 'input.csv'
lines = []
with open(path, newline='', encoding='utf-8') as f:
data = csv.reader(f, delimiter='|', skipinitialspace=True)
for row in data:
lines.append([c.strip() for c in row])
print(lines)
This removes all leading and trailing spaces from each cell in a row using the strip()
command. 这将使用
strip()
命令从一行中的每个单元格中删除所有前导和尾随空格。 Depending on your data, it might be just enough to add the additional skipinitialspace=True
parameter. 根据您的数据,添加附加的
skipinitialspace=True
参数可能就足够了。 This though would not remove trailing spaces before the next delimiter. 但是,这不会删除下一个定界符之前的尾随空格。
newline=''
should also be used in Python 3.x when used with a csv.reader()
. 当与
csv.reader()
一起使用时, newline=''
也应在Python 3.x中使用。
The file you have given just contains lines of text, as such you could read it as follows: 您提供的文件仅包含文本行,因此您可以按以下方式阅读:
lines = []
with open('input.csv', encoding='utf-8') as f_input:
for line in f_input:
lines.append(line.strip())
print(lines)
This would give you lines
containing: 这将使您的
lines
包含:
['Sistem en az 23.8 inç boyutlarında olmalıdır.', '1 adet HDMI port olmalıdır.']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.