每当我尝试读取 Python 中的文件时,我都会收到错误消息,我该如何解决?

I get an error whenever I try to read a file in Python, how can I fix this?

我的代码:

String = open(r"C:\Users\chloe\OneDrive\Documents\Python\Python code\Python text files\Story\VerbJust.txt", "r").read()
print(String)

我将文件存储在确切的文件夹中,但出现错误:``

Traceback (most recent call last):   
  File "C:\Users\chloe\OneDrive\Documents\Python\Python code\StoryClasses.py", line 47, in <module>     
    VerbTo = ReadFile("VerbTo")   
  File "C:\Users\chloe\OneDrive\Documents\Python\Python code\StoryClasses.py", line 41, in ReadFile     
   string = open(w[variable][0], "r").read() 
FileNotFoundError: [Errno 2] No such file or directory: 'C'

这是为什么? Python 不能访问 OneDrive 吗?

出现此错误是因为引号格式不正确。

此外,我怀疑您选择的变量名称“String”可能会导致一些问题。

尝试:

string = open(r"filepath", "r").read()
print(string)

这一行:

string = open(w[variable][0], "r").read()

似乎 w[variable] 包含文件名。添加 [0] 仅使用文件名的第一个字符。摆脱那个。

string = open(w[variable], "r").read()