每当我试图读取Python中的文件时,都会出现错误,如何修复?

2024-09-30 01:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

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吗


Tags: inpyreadstringlinecodeonedriveopen
2条回答

在这方面:

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

似乎w[variable]包含文件名。将[0]添加到只使用文件名的第一个字符的文件中。把它扔掉

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

发生此错误的原因是引号格式不正确

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

尝试:

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

相关问题 更多 >

    热门问题