我有一个csv文件内容。这里的分隔符是|我想删除行中的空格。我尝试用|分隔文件并且去掉空间的每个元素但是当把它写到新的csv时,空间被引入回来。在python中干掉所有这些
| 1497/1 | ACERNO-1 | 1 | 99000010119101 | RUCOPY:数据库树副本| LEGACY_DATA | 283 | OFDB_IT_SIEP |
import csv
aList=[]
workingdir = r"C:\Users\Akshay.Jain\Desktop\CAREER CONNECT"
csvfile = workingdir+r"\01_Wells.csv"
out = csv.writer(open("myfile.csv","w",newline=''),delimiter=',')
with open(csvfile, 'r') as f:
reader = csv.reader(f, skipinitialspace=True,delimiter='|', quoting=csv.QUOTE_NONE)
for row in reader:
for elements in row:
elements.strip()
aList.append(row)
out.writerow(row)
答案 0 :(得分:1)
你的行
out.writerow(row)
再次写入原始row
。尝试像
out.writerow(aList)
(创建aList
移入循环并将elements
添加到aList
)或直接修改row
,正如@mgilson在评论中指出的那样:
for row in reader:
row = [x.strip() for x in row]
out.writerow(row)
答案 1 :(得分:0)
import csv
aList=[]
workingdir = r"C:\Users\Akshay.Jain\Desktop\CAREER CONNECT"
csvfile = workingdir+r"\01_Wells.csv"
out = csv.writer(open("myfile.csv","w",newline=''),delimiter=',')
with open(csvfile, 'r') as f:
reader = csv.reader(f, skipinitialspace=True,delimiter='|', quoting=csv.QUOTE_NONE)
for row in reader:
for elements in row:
elements.strip()
aList.append(elements[:-1]) # Add element by element, removing last item.
out.writerow(aList[1: -1]) # Write list without first or last item, they are ","
输出:
1497/1,ACERNO-1,1,99000010119101,RUCOPY :Database tree copy,LEGACY_DATA,283,OFDB_IT_SIEP