Python - 通过循环将多个数据插入多个数组

时间:2018-01-20 17:38:13

标签: python arrays loops csv

我目前有3个不同的csv文件和一些数据。我想将数据插入3个不同的数组。这是我目前正在编写的编码

 public class LongOperation extends AsyncTask<Void, Void, Void> {


        @Override
        public Void doInBackground(Void... voids) {

              for (String imagePath : selectedImages) {   //this is the second for loop which might be running only once  
                File sourceImage = new File(imagePath); //returns the image File from model class to
                // be// moved.

                File destinationImage = new File(al_images.get(id).getDirectoryPath() +
                        File.separator + sourceImage.getName());

                try {
                    moveFile(sourceImage, destinationImage, false);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

     private void moveFile(File file_Source, File file_Destination, boolean isCopy) throws IOException {
        FileChannel source = null;
        FileChannel destination = null;
        if (!file_Destination.exists()) {
            file_Destination.createNewFile();
        }

        try {
            source = new FileInputStream(file_Source).getChannel();
            destination = new FileOutputStream(file_Destination).getChannel();

            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, count, size - count)) < size) ;
            if (!isCopy) {
                file_Source.delete();
                MediaScannerConnection.scanFile(this,
                        new String[] { file_Source.toString() }, null,null);
            }
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }


    }

我知道代码肯定不会起作用。有没有办法让我能做到?

1 个答案:

答案 0 :(得分:1)

试试这个。它会生成一个包含三个列表的列表。顺便说一下,在Python中没有像Java那样的“数组列表”。只有一个“列表”,其行为类似于Java ArrayList。

arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index),'r') as f:
        temparr=[]
        for line in f:
            if line != '':
                temparr.append(line)
        arrayList.append(temparr)

使用CSV模块:

import csv
arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index), 'rb') as f:
        reader = csv.reader(f)
        arrayList.append([row for row in reader])