我想提取文件夹中的文件并列出文件夹中文件的名称,将它们放入数据框中并列出单个数据框中的所有内容。
我使用了以下代码:
# Import the os module
import os
# Define the path to the file
file_path = "C:/Users/844444/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset" # folder path
# list all the files in the folder
files = os.listdir("C:/Users/844444/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset")
print(files)
我收到以下错误消息
<>:5: SyntaxWarning: invalid escape sequence '\D'
<>:8: SyntaxWarning: invalid escape sequence '\D'
<>:5: SyntaxWarning: invalid escape sequence '\D'
<>:8: SyntaxWarning: invalid escape sequence '\D' C:\Users\844444\AppData\Local\Temp\ipykernel_2768\3354836572.py:5: SyntaxWarning: invalid escape sequence '\D'
file_path = "C:/Users/879304/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset" # folder path C:\Users\844444\AppData\Local\Temp\ipykernel_2768\3354836572.py:8: SyntaxWarning: invalid escape sequence '\D'
files = os.listdir("C:/Users/879304/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset")
发生这种情况是因为字符串中的字符
\D
(在\Dataset
中)被解释为转义序列(有关转义序列的Python文档)——例如,"\n"
意味着换行。
为了避免这种行为,您可以将反斜杠
\
替换为两个反斜杠 \\
(这是单个反斜杠的转义序列),或者在字符串前面添加 r
,如下所示:
file_path = r"C:/Users/844444/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset" # folder path
# list all the files in the folder
files = os.listdir(r"C:/Users/844444/OneDrive -
hull.ac.uk/T3\Dataset/Crystal Clean-Brain Tumors
MRI Dataset")
print(files)
这告诉 Python 避免解释转义序列