删除特定csv fi中的前导0

2024-04-18 21:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件叫做新建.csv我正在尝试删除某个名为code的列中的所有前导0。你知道吗

id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,micheal,030

这只是csv文件的一个示例,除了有近1000行之外。我只想从代码列中删除前导的0。你知道吗

我试图找到一个解决方案,我可以编辑一个完整的列为未来的参考了。例如,假设有一个要从列中删除的主角“k”。你知道吗

我在网上看到了一些例子,但并不奏效。你知道吗

这就是我们下面所说的

import pandas as pd
import sys

with open('new.csv') as infile:
    title = next(infile)
    infile.seek(0)
    table = pd.read_csv(infile)

table.rename(columns={'Unnamed: 2':''}, inplace=True)

table['code'] = table['code'].str.replace("0", "")
sys.stdout.write(title)
table.to_csv(sys.stdout, ',', index=False)

Tags: 文件csvnamebrimportidtitleas
3条回答

您可以使用regexre.sub轻松地替换前导零。使用这个正则表达式

0+([1-9][0-9]*)

替换为\1基本上是group1内容

Demo

试试这些Python代码

import re

s = '''id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,micheal,030'''

print(re.sub(r'0+([1-9][0-9]*)', r'\1', s))

打印不带前导零的数字

id,name,code <br>
0,kevin,10 <br>
1,john,11 <br>
2,casey,20 <br>
3,micheal,30

编辑:

您可以创建这种函数,它将文件名作为参数,并生成一个名为inputfilename.out的新文件

import re
from shutil import move
from os import remove


def remove_leading_chars(inputfile):
    with open(inputfile, 'r', encoding="utf-8") as infile, open(inputfile+'.out', 'w', encoding="utf-8") as outfile:
        for s in infile.readlines():
            s = re.sub(r',m+', r',', s)
            outfile.write(s)


remove_leading_chars('data.txt')
remove('data.txt')
move('data.txt.out', 'data.txt')
print('writing done')

输入文件的内容data.txt

id,name,code <br>
0,mmmkevin,010 <br>
1,mmmjohn,011 <br>
2,mmmcasey,020 <br>
3,mmmicheal,030

覆盖data.txt文件的内容

id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,icheal,030

以我为例:

txt = '''id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,micheal,030'''
txt = txt.split('\n')
txt = [i.rpartition(',') for i in txt]
txt = [''.join([i[0],i[1],i[2].lstrip('0')]) for i in txt]
txt = '\n'.join(txt)
print(txt)

输出:

id,name,code <br>
0,kevin,10 <br>
1,john,11 <br>
2,casey,20 <br>
3,michaeal,30

注意,为了简单起见,我硬编码了txt内容。我使用str方法:rpartition最后分裂,lstrip去除0。你知道吗

编辑:您可以将.csv视为纯文本文件,并使用read获取内容,即不必硬编码txt只需执行以下操作:

with open('yourfile.csv','r') as f:
    txt = f.read()

在结束时,不要打印txt,而是执行以下操作:

with open('yournewfile.csv','w') as f:
    f.write(txt)

您应该尝试使用字符串片段删除0,例如:

table['code'] = table['code'].str[1:]

另外,如果0后面有一个逗号,比如:0,,那么试着用这个来代替:

table['code'] = table['code'].str[2:]

相关问题 更多 >