Array column separations for beginners

Peter Otten __peter__ at
Wed Apr 26 10:29:27 EDT 2017

katarin.bern at wrote:

> Hi,
> 1. I would like to ask how can I adjust array.csv like this:
> ,,,-00.000146400000,   0.08000,
> ,,,-00.000146200000,   0.00000,
> ,,,-00.000146000000,   0.00000,
> ,,,-00.000145800000,   0.00000,
> so I can have in first column -00.000146400000 and in second column
> 0.08000? (thanks, I am begginer).

Have a look at the csv module

You can use the reader class to read the rows and the writer to write the 
result to a new file.

(All code untested)

with open("array.csv") as infile:
    reader = csv.reader(infile)
    with open("out.csv", "w") as outfile:
        writer = csv.writer(outfile)
        for row in reader:
            writer.writerow([row[3], row[4]])

> 2. How can I pick out information(number) from 20 separate files to one
> file? (thanks!)

Do you know how to extract the number from one file? Put the code into a 

def pick_number(filename):
    ...  # open the file, extract the number
    return number

Then specify the filenames:

sourcefiles = ["foo.txt", "bar.txt", ...]

If the list of filenames is not fixed have a look at the glob module.


sourcefiles = glob.glob("/path/to/*.txt")  # all txt files in the /path/to
                                       # directory

Finally loop over the files and write out the numbers:

with open("/path/to/outfile.txt", "w") as outfile:
    for filename in sourcefiles:
        print(pick_number(filename), file=outfile)

More information about the Python-list mailing list