Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取CSV数据时删除特定字符串_Python_Csv - Fatal编程技术网

Python 读取CSV数据时删除特定字符串

Python 读取CSV数据时删除特定字符串,python,csv,Python,Csv,我是python新手,我正在编写一个从CSV文件读取数据的代码 数据如下所示: 10944750,13451,0,6��4�� 10944750,21110,0,6��7�� 10944750,1131,0,7��23�� 10944750,8689,0,5��2�� 最后一列表示日期,例如第一行中的日期:6月4日。但其中有两个中国宪章。所以我必须解码它,得到月份和日期 我的代码: import codecs raw_file=open('Documents/t_alibaba_d

我是python新手,我正在编写一个从CSV文件读取数据的代码

数据如下所示:

10944750,13451,0,6��4��   

10944750,21110,0,6��7��

10944750,1131,0,7��23��

10944750,8689,0,5��2��
最后一列表示日期,例如第一行中的日期:6月4日。但其中有两个中国宪章。所以我必须解码它,得到月份和日期

我的代码:

import codecs
raw_file=open('Documents/t_alibaba_data.csv')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
    entry=line.split(",")
    deco=entry[3].decode("gbk")
    month=deco[0]
    if len(deco)==5:
        day=int(deco[2])*10+int(deco[3])
    else:
        day=int(deco[2])
    result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
        print result

我的IDE中没有警告或错误,但我的结果中也没有任何内容。

首先:您没有告诉Python您要从文件中读取。(将“r”添加到原始文件.open()

在运行程序时,在解码最后一列之后,元素nr3(deco[2])是一个中国符号,而不是一天的nr

我对你的程序做了一点调整,当它看起来像这样时,它就工作了(至少如果我正确理解了你的问题):

此外,len(deco)永远不会为5,if测试也永远不会为真。长度始终大于5。请尝试打印不同deco的长度,以查看实际长度。
在deco上使用strip函数可能是明智的,以防字符串末尾有空格。当我打印您作为示例给出的deco的长度时,长度是8或9,这取决于正在处理的行。

既然它是文件对象,为什么要打印
结果
?如果打印
日怎么办
?而且,在您的情况下,不会有十一月或十二月,对吗?我删除了result.txt中的最后一句话,没有任何内容。不会有十一月或十二月,如果您在循环中删除了
result.flush()
result.close()
result.close()或
result.flush()
result.close())循环结束时。谢谢,我发现在mac os和windows中,当我
deco=entry[3]。解码(“gbk”)
打印deco
时,屏幕上的结果是不同的。在windows中看起来像
6月4.日,在mac中是这样的
/u11111/u111/n
import codecs
raw_file=open('Documents/t_alibaba_data.csv', 'r')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
    entry=line.split(",")
    deco=entry[3].decode("gbk").strip()
    month=deco[0]
    if len(deco)==5:
        day=int(deco[2])*10+int(deco[3])
    else:
        day=int(deco[4])
    result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
result.close()