简体   繁体   中英

Replace column separation of # with comma or tab

This question may be very simple and easy. The column of my data file is separated by # instead of tab or comma. Such as: 123#142#5#98#......

In this format, it seems that I can't read whole value of 123 or 142 when I tried to read a value in one column at certain line.

Do you have any idea to solve this issue such as changing # to true separation like tab or comma?

I will really appreciate any help or idea.

Thank you, Isaac

When reading, you can use csv.reader() which takes a delimiter parameter like this:

>>> with open(your_file, "r") as f:
...    data = [x for x in csv.reader(f, delimiter='#')]
...
>>>

And when you're writing, csv.writer() accepts the same parameter..

>>> with open("foo.txt", "w") as f:
...    w = csv.writer(f, delimiter=',')
...    w.writerows(data)
...
>>>

Here's a combined example:

>>> with open("test.csv", "r") as inp, open("foo.csv", "w") as out:
...     w = csv.writer(out, delimiter=",")
...     w.writerows(x for x in csv.reader(inp, delimiter="#"))
...
>>>

Contents of test.csv :

123#142#5#98
foo#bar#baz#baf

Contents of foo.csv :

123,142,5,98
foo,bar,baz,baf

you have data then

    data ='123#142#5#98#1234'
    data_list=data.split('#')

    for each_element in data_list:
           print each_element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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