在Python 3.6中重命名特定文件

时间:2018-02-19 10:47:15

标签: python python-3.x loops

public class CSVFile
{
    private ArrayList<String[]> arrLs = new ArrayList<>();
    private Object OneRow;

    public ArrayList<String[]> ReadCSVFile(File DataFile)
    {
        try
        {    
            //BufferedReader to Read through CSV Contents
            BufferedReader reader = new BufferedReader (new FileReader(DataFile));
            String line;

            // while loop to read through the data, while bufferedreader is not null-do .... 
            while(reader.readLine()!= null)
            {
                try
                {
                    line = reader.readLine();

                    if(line != null)
                    {
                        String[] array = line.split(",");

                        for(String result:array)
                        {
                            //System.out.println(OneRow[2]+");
                            System.out.println(result);
                        }
                    }                      
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                finally
                {
                    if(reader == null)
                    {
                        reader.close();
                    }
                }

                //if statement needed in the case the 
                //Selected CSV has more than the required number of ColumnHeaders
                //and the BufferedReader needs to skip the first Row, as this is the 
                //columnHeaders and they cannot be included again
                String read = reader.readLine();//bufferedreader string variable
                OneRow = read.split(",");
                arrLs.add((String[]) OneRow);
                // System.out.println(Arrays.toString(OneRow));
            }//end try 
            catch(Exception ex)
            {
                 String errmsg = ex.getMessage();
                 //System.out.println("File not Found: "+errmsg);
            }    // end exception handling

            return (ArrayList<String[]>) arrLs;
        }   //End of ArrayList_readCSVFile class
    } //End of CSVFile class
}

我想更改第2,第4和第6个文件的文件名,如更改列表中所示。但我只能更改第二个文件的文件名。 j值不是迭代的。我尝试删除break但它给我错误说无法找到指定的文件。 请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

试试这个:

for index, name in enumerate(newList):
    if index in toChange:
        newName = name.replace(name, str(index))
        os.rename(name, newName)
        print(newName)

Index是newList中每个变量的索引。然后你检查这个索引是否在你的列表中改变。如果是,则更改文件名。

枚举:

for index, number in enumerate([10, 20, 30]):
        print('index -> {}'.format(index))
        print('number -> {}'.format(number))

>>>
 index -> 0
 number -> 10

 index -> 1
 number -> 20

 index -> 2
 number -> 30

如何工作&#39;

2 in [1,2,3]
>> True
2 in [1,3]
>> False