How do I parse a listing of files to get just the filenames in Python?

前端 未结 7 1696
一向
一向 2021-02-10 23:50

So lets say I\'m using Python\'s ftplib to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) ins

7条回答
  •  没有蜡笔的小新
    2021-02-11 00:28

    Since every filename in the output starts at the same column, all you have to do is get the position of the dot on the first line:

    drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .

    Then slice the filename out of the other lines using the position of that dot as the starting index.

    Since the dot is the last character on the line, you can use the length of the line minus 1 as the index. So the final code is something like this:

    lines = ftp.retrlines('LIST')
    lines = lines.split("\n") # This should split the string into an array of lines
    
    filename_index = len(lines[0]) - 1
    files = []
    
    for line in lines:
        files.append(line[filename_index:])
    

提交回复
热议问题