I want to know

I want to write the Java program below in Python.

File f = new File ("D: \\ Desktop \\ recipe");
if (f.isDirectory ()) {
    String [] fileList = f.list ();
    for (int j = 0;j<fileList.length;j ++) {
        BufferedReader br = new BufferedReader (new FileReader (fileList [j]));
        String line;
        while ((line = br.readLine ())! = null {#something}

How do you write it in Python?

I checked and wrote it myself, but the loop didn't stop. (#In some processing, if print ("a") was tried, a continued to be output.)
There are some csv files in D: \\ Desktop \\ recipe.

import os
if os.path.isdir ('D: \\ Desktop \\ recipe'):
    fileList = os.listdir ('D: \\ Desktop \\ recipe')
    for j in range (len (fileList)):
        f = open ('D: \\ Desktop \\ recipe \\' + fileList [j], 'r', encoding = 'utf-8')
        line = f.readlines ()
        while line is not None:
  • Answer # 1


    The loop did not stop.

    There is a problem with the loop.
    Unlike the Java method, the line cannot be rewritten in the loop.

    line = f.readlines ()
    while line is not None:
        # Do something

    If you want to implement the loop in Pythonic, it would be natural to write

    for line in f:
        # Do something

    In addition, using pathlib instead of os.path will give you more modern code.
    Qiita-If you use Python3.4 or later, you should discard os.path and use pathlib

    Because the original Java code is also legacy, it's hard to get ...

    for j in range (len (fileList)):

    It's not a mistake, but usually you don't do this.
    A timely article was posted, so I'll put a link here.
    Qiita-Let's start programming with Python! ~ How to use for statement ~

  • Answer # 2

    No need for Python. Yes, shell art!

    PS>gci 'D: \ Desktop \ recipe' -File |% {gc -en UTF8 $_. FullName} |% {Something}}

Related articles