当文件名包含点时,读取.txt文件名

2024-03-28 09:55:20 发布

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

我想打开一个名为“x.1.1.1.txt”的文件名。但我遇到了问题因为那几个点。在

    f=open('x.1.1.1.txt','r')

当我使用这个函数时,我得到的消息是文件名不存在。在

谢谢


Tags: 函数txt消息文件名open
1条回答
网友
1楼 · 发布于 2024-03-28 09:55:20

只要提供的路径正确,文件所在的位置并不重要。在

在下面的例子中,我自己在变量中指定文件的路径。示例文本文件位于my documents文件夹中。该文件的内容是一行文本示例。在

尝试:

#if using windows filepath maybe C:\User\username\Documents
#if using mac filepath maybe /Users/username/Documents/
filepath = r'whole_path_to_file\x.1.1.1.1.1.txt'
o = open(filepath, 'r')
r = o.readlines()
print(r)
#output of example file nameed x.1.1.1.1.1.txt
['File content to read']

希望有帮助。在

相关问题 更多 >