Search code examples
pythonexcelfilenames

os.listdir() adds characters to the beginning of file name?


I had a quick google of this but couldn't find anything. I'm using os to get a list of all the file names in the current working directory using the following code:

path = os.getcwd()
files = os.listdir(path)

The list of files returns fine, but the last element has an extra '~$' that isn't in the actual file name. For example:

files
['File1.xlsx', 'File2.xlsx', '~$File3.xlsx']

This is then causing an issue when I iterate through these files to try and import them, as I get the error of:

[Errno 2] No such file or directory: 'C:\\Users\\$File3.xlsx'

If anyone knows why this happens and how I can fix/prevent it, that would be great!


Solution

  • Just thought I'd answer in case anyone else has this issue.

    It's nothing to do with os. It happened because I had File3 open in Excel while pulling the list of file names. I've found out that opening a microsoft document creates a temporary 'lock' file, which are denoted by '~$' (this is how it can re-open unsaved data if it crashes etc).

    I found the below from here:

    The files you are describing are so-called owner files (sometimes referred to as "lock" files). An owner file is created when you work with a document ... and it should be deleted when you save your document and exit.

    There's also a SO question about this within Microsoft files, which can be found here