从csv文件中删除特定字符,然后重写为新文件 [英] Remove specific character from a csv file, and rewrite to a new file

查看:122
本文介绍了从csv文件中删除特定字符,然后重写为新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个VBA宏,每隔5分钟就会在整个纽约证券交易所提取股票数据.这将拉动所有因素,从当前价格到获利日期,再到市盈率以及其他指标.我现在正试图设置一个cronjob,以运行一些python代码来清理csv数据,然后再将其导入到mySQL数据库中.在设置cronjob之前,我需要先运行python代码...宝贝步骤:).

I have a VBA macro pulling stock data every 5 minutes on the entire NYSE. This pulls everything from current price, to earnings dates, to p/e, among other metrics. I'm now trying to set up a cronjob to run a little python code to clean up the csv data before I import it into the mySQL database. Before I can set up the cronjob, I need to get the python code working... Baby steps :).

几年前,我不再使用python,但在这里尝试再次使用它.经过一些研究,经过审核,他们在2.6中删除了许多字符串方法,然后在3.1中删除了maketrans()参数.我正在运行python 3.3.

I went away from python a few years ago, but am trying to use it again here. After some research, it's been vetted that back in 2.6 they removed many of the string methods, followed by the maketrans() argument in 3.1. I'm running python 3.3.

下面有人对我的代码有任何建议吗?我一次拉入csv文件的1行,并尝试用任何符号('')替换百分号(%).我试过在if语句中使用replace()参数,但这也不起作用.非常感谢.

Does anyone have any suggestions for my code below? I'm pulling in 1 line of the csv file at a time, and trying to replace the percent sign (%), with nothing (''). I've tried using the replace() argument within an if statement, but that's not working either. Many, many thanks in advance.

谢谢

import csv
import string

input_file = open('StockData.csv', 'r')
output_file = open('Output.csv', 'w')
data = csv.reader(input_file)
writer = csv.writer(output_file)
specials = '%'

for line in data:
    trans = s.makestrans(specials, ''*len(specials))
    new_line = line.translate(trans)
    writer.writerow(new_line)

input_file.close()
output_file.close() 

推荐答案

感谢大家的帮助-以下是我收到结果的代码.我使用了help(string.split)来使我的数据在替换后出现在正确的列中.另外,关键是将line设为字符串,以便进行替换.

Thanks for the help from everyone - below is the code that I got to receive my result. I used help(string.split) in order to get my data to appear in the correct columns after the replacement. Also, the key was making line a string, in order to do the replacement.

import csv
import string

input_file = open('DesktopData.csv', 'r')
output_file = open('fixformat.csv', 'w')
data = csv.reader(input_file)
writer = csv.writer(output_file,quoting=csv.QUOTE_ALL)# dialect='excel')
specials = '%'

for line in data:
    line = str(line)
    new_line = str.replace(line,specials,'')
    writer.writerow(new_line.split(','))

input_file.close()
output_file.close()

这篇关于从csv文件中删除特定字符,然后重写为新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆