40
def choose_option(self):
        if self.option_picker.currentRow() == 0:
            description = open(":/description_files/program_description.txt","r")
            self.information_shower.setText(description.read())
        elif self.option_picker.currentRow() == 1:
            requirements = open(":/description_files/requirements_for_client_data.txt", "r")
            self.information_shower.setText(requirements.read())
        elif self.option_picker.currentRow() == 2:
            menus = open(":/description_files/menus.txt", "r")
            self.information_shower.setText(menus.read())

I am using resource files and something is going wrong when i am using it as argument in open function, but when i am using it for loading of pictures and icons everything is fine.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
eugene
  • 409
  • 1
  • 4
  • 3
  • 11
    For someone else that gets a similar error, you may have invalid characters (for example `:` or `?`) in the filename. – George Ogden Sep 10 '20 at 09:26
  • 3
    Another scenario (that I just ran into) is if you are trying to write to a file inside a DropBox folder and you just had that file open very recently, you can run into this same error caused by DropBox has detected the changes and is attempting to process your new file. – royce3 May 29 '21 at 03:37
  • Ditto, this can also be the case for a OneDrive file. – Isaacnfairplay Sep 12 '22 at 13:48

21 Answers21

52

That is not a valid file path. You must either use a full path

open(r"C:\description_files\program_description.txt","r")

Or a relative path

open("program_description.txt","r")
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
14

Add 'r' in starting of path:

path = r"D:\Folder\file.txt"

That works for me.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
shailu
  • 190
  • 1
  • 10
12

I also ran into this fault when I used open(file_path). My reason for this fault was that my file_path had a special character like "?" or "<".

tuomastik
  • 4,559
  • 5
  • 36
  • 48
wolfog
  • 731
  • 7
  • 10
8

I received the same error when trying to print an absolutely enormous dictionary. When I attempted to print just the keys of the dictionary, all was well!

duhaime
  • 25,611
  • 17
  • 169
  • 224
5

For me this issue was caused by trying to write a datetime to file.

Note: this doesn't work: myFile = open(str(datetime.now()),"a")

The datetime.now() object contains the colon ''':''' character

To fix this, use a filename which avoid restricted special characters. Note this resource on detecting and replacing invalid characters: https://stackoverflow.com/a/13593932/9053474

For completeness, replace unwanted characters with the following:

import re

re.sub(r'[^\w_. -]', '_', filename)

Note these are Windows restricted characters and invalid characters differ by platform.

Jacob Waters
  • 307
  • 1
  • 3
  • 11
4

In my case, I was using an invalid string prefix.

Wrong:

path = f"D:\Folder\file.txt"

Right:

path = r"D:\Folder\file.txt"
Rafs
  • 614
  • 8
  • 19
4

In my case the error was due to lack of permissions to the folder path. I entered and saved the credentials and the issue was solved.

Nick Green
  • 101
  • 1
  • 9
3

I had the same problem It happens because files can't contain special characters like ":", "?", ">" and etc. You should replace these files by using replace() function:

filename = filename.replace("special character to replace", "-")
Lio Ak
  • 41
  • 2
2

you should add one more "/" in the last "/" of path, that is: open('C:\Python34\book.csv') to open('C:\Python34\\book.csv'). For example:

import csv
with open('C:\Python34\\book.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='', quotechar='|')
    for row in spamreader:
        print(row)
Charlie Joynt
  • 4,411
  • 1
  • 24
  • 46
Hiep Tran
  • 3,735
  • 1
  • 21
  • 29
  • 1
    Welcome to Stack Overflow! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Enamul Hassan Jan 05 '16 at 16:14
  • 7
    There's a set of problems with this answer: 1) `open('C:\Python34\book.csv')` to `open('C:\Python34\book.csv')` -> There is no difference between the two lines. Did you mean `open('C:\Python34\book.csv')` to `open('C:\\Python34\\book.csv')`? 2) Both the code in the example and in the first line is wrong, as you're not escaping backslashes (or, in the case of your example, all of them.) `'C:\Python34\\book.csv'` should be `'C:\\Python34\\book.csv'` or `r'C:\Python34\book.csv'` – GPhilo May 31 '17 at 09:41
  • 1
    If you click Edit you'll see that @hiep-tran did type double slashes, but SO rendered these as single slashes. I fixed the formatting with backticks around the example commands. – Charlie Joynt Mar 15 '18 at 10:59
2

In Windows-Pycharm: If File Location|Path contains any string like \t then need to escape that with additional \ like \\t

stderr
  • 8,567
  • 1
  • 34
  • 50
Abhijeet
  • 8,561
  • 5
  • 70
  • 76
2

Just replace with "/" for file path :

   open("description_files/program_description.txt","r")
P113305A009D8M
  • 344
  • 1
  • 4
  • 13
2

just use single quotation marks only and use 'r' raw string upfront and a single '/'

for eg

f = open(r'C:/Desktop/file.txt','r')
print(f.read())
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

I had special characters like '' in my strings, for example for one location I had a file Varzea*, then when I tried to save ('Varzea.csv') with f-string Windows complained. I just "sanitized" the string and all got back to normal.

The best way in my case was to let the strings with just letters, without special characters!

0
for folder, subs, files in os.walk(unicode(docs_dir, 'utf-8')):
    for filename in files:
        if not filename.startswith('.'):
            file_path = os.path.join(folder, filename)
Prostak
  • 3,565
  • 7
  • 35
  • 46
0

In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.

Mohsen Hrt
  • 263
  • 2
  • 9
0
import pandas as pd
df = pd.read_excel ('C:/Users/yourlogin/new folder/file.xlsx')
print (df)
I Iv
  • 21
  • 1
0

I got this error because old server instance was running and using log file, hence new instance was not able to write to log file. Post deleting log file this issue got resolved.

Abhishek Gaur
  • 695
  • 8
  • 11
0

When I copy the path by right clicking the file---> properties-->security, it shows the error. The working method for this is to copy path and filename separately.

0

I had faced same issue while working with pandas and trying to open a big csv file:

wrong_df = pd.read_csv("D:\Python Projects\ML\titanic.csv")
right_df = pd.read_csv("D:\Python Projects\ML\\titanic.csv")

Martin Faucheux
  • 884
  • 9
  • 26
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '22 at 19:28
0

I had the same problem

My fault was: with open(f'file{a}{b}{c}{d}{e}{f},'w') as f: <code>

i tried to open the file as f containing f in filename

caution using with and as <variable> when opening a file

Qwerth
  • 21
  • 6
0

I faced the same issue, I have resolved it by creating a function that converts backslashes to forward slashes. Probably, this may not be the best way but it fixed my issue.

bs = r"\""
fs = "\\"    
def bs_to_fs(folder_path):
    folder_path_with_forw_Slash = ""
    for i in folder_path:
        if i == bs:
            folder_path_with_forw_Slash = folder_path_with_forw_Slash+'/'
        else:
            folder_path_with_forw_Slash = folder_path_with_forw_Slash+i
    folder_path_with_forw_Slash = folder_path_with_forw_Slash + fs[:1] 
    return(folder_path_with_forw_Slash)

Folder_path = r"E:\Random_Files\Project1"
open_file_name = "Some_File_Name.txt"

FILE_TO_OPEN = bs_to_fs(Folder_path) + op_file_name

with  open(FILE_TO_OPEN,'w') as file1:

Then Continue with rest of your code

ArunC
  • 1
  • 1