简体   繁体   English

如何在Windows中使用python打开文件?

[英]how to open file in windows with python?

I'm passing the file name trough sys.argv with slashes not backslashes . 我通过斜线而不是反斜线传递文件名sys.argv。 I'm using os.path.normpath and os.path.join but when trying to open the file I get an exception no such file or directory: and the path is with double backslashes. 我正在使用os.path.normpath和os.path.join,但是尝试打开文件时出现异常,没有此类文件或目录:并且路径带有双反斜杠。 I'm searching for the solution for hours but nothing works. 我正在寻找解决方案数小时,但没有任何效果。

I'v tried every tutorial I could find on google and I just keep getting the same problem. 我尝试了所有可以在Google上找到的教程,但我一直都遇到同样的问题。 I just keep getting double back slashes. 我只是不断得到双反斜杠。 I've tried also just hardcoding the path like in example. 我也尝试过像示例中那样对路径进行硬编码。

filepath = os.path.normpath(os.path.join('D:/dir1/dir2/dir3', 'myfile.txt'))
try:
    my_file = open(filepath, 'w+')
except Exception as e:
    print('Cannot create/open file w+!\n{}'.format(e))

I've need to be able to open the file. 我需要能够打开该文件。

I would prefer to keep my files in a structured format where my main script will be in the root folder. 我希望将文件保留为结构化格式,其中我的主脚本位于根文件夹中。 This approach becomes more generic in a sense that if you try to run the same content on some other system with the different operating system, the path will raise issues. 从某种意义上说,这种方法变得更加通用:如果您尝试在其他具有不同操作系统的系统上运行相同的内容,那么路径将引发问题。

Example

Project
  |-- main.py
  |-- files
       |--file1.txt
       |--file2.txt

Then you can simply access files by 然后,您可以通过以下方式简单地访问文件

with open("files/file1.txt", 'w+') as file_object:
    content = file_object.readlines() # Whatever the method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM