pythononedrivewindows-security

How can I fix FileNotFoundError in Python when writing to a file in a OneDrive directory?


My OS is Windows, newest version and all updated, I think the issue lies in the path or something to do with OneDrive.

Using the code:

file = "dataset.csv"
with open(file, "w") as f:
    f.write(data)

I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'dataset.csv', but this is an error I have never had before...

I have enabled long paths in the Windows registry and rebooted and it still does not work.

However, I have tried to run this code in different paths of my pc, and it does work if I run it in the path or with a shorter path than: C:\Users\user\OneDrive - UniversityX XXXXXXXXXX XXXXXXXX\XXXXXXXXX, where X is also part of the folder name as it is my unversity`s name. If I run it after that path it just stops working and outputs that error every time I run the code in VSCode.

Update: This does not only not work in VSCode, but if I use matlab or any other program to save a file, it does not let me save the file either as it says that the file cannot be found.

Does anyone know how I can fix this, please?


Solution

  • I found out that it was a Windows Security issue in the end... I enabled controlled folder access. To disable this follow these steps:

    1. Settings > Update & Security (Windows 10) or Privacy & Security (Windows 11) > Windows Security > Virus & threat protection.
    2. Under Virus & threat protection settings, select Manage settings.
    3. Under Controlled folder access, select Manage Controlled folder access.
    4. Switch the Controlled folder access setting to Off.

    This option apparently blocks any program from creating new files in certain directories.