简体   繁体   English

删除python文件中每行逗号前的所有字符

[英]Remove all characters before comma of every line in a file in python

I need a small function in python that would read in a file and then remove all the characters up to AND INCLUDING a comma character. 我需要python中的一个小功能,该功能可以读入文件,然后删除所有字符,直到并包括逗号字符。 so for instance the following two line file: 因此,例如以下两行文件:

hello,my name is
john,john, mary

would be: 将会:

my name is
john, mary

You have been advised to use re.split() already; 建议您已经使用re.split()了; however, regular split() method of str should suffice as well: 但是, str常规split()方法也应足够:

with open('new_file', 'w') as f_out, open('my_file') as f_in:
    for line in f_in:
        new_str = ','.join(line.split(',')[1:])
        f_out.write(new_str)

What you want is called Regular Expressions . 您想要的就是正则表达式 Specifically, the split should work well. 具体来说, 拆分应该工作良好。

vals=re.split(',',string,1) vals = re.split(',',string,1)

also: 也:

line = 'hello,my name is'
line[line.find(',')+1 :  ]     #find position of first ',' and slice from there
>>> 'my name is'

Use partition 使用分区

>>> foo = 'hello, my name is'
>>> foo.partition(',')[2]
' my name is'
>>> foo = 'john, john, mary'
>>> foo.partition(',')[2]
' john, mary'
>>> foo = 'test,'
>>> foo.partition(',')[2]
''
>>> foo = 'bar'
>>> foo.partition(',')[2]
''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM