【问题标题】:SyntaxError: EOL while scanning string literal, Does not Create and Write to FileSyntaxError:扫描字符串文字时 EOL,不创建和写入文件
【发布时间】:2020-10-03 18:53:06
【问题描述】:

我正在尝试在 APPDATA\Roaming 目录中创建一个文件,然后将一些文本写入该文件。 它是一个文本文件,因此不能按预期工作

我将其视为错误

C:\pytut>python appdatapath.py
  File "appdatapath.py", line 4
    file = path + "\" + 'keys.txt'
                                 ^
SyntaxError: EOL while scanning string literal

我能说什么可能是错的?我的代码如下所示

import os

path = os.getenv('APPDATA')
file = path + "\" + 'keys.txt'

with open(file,'w') as f:
     data = 'Hello Jasmine!'
     f.write(data)
print('Done!')

请在我弄错的地方提供帮助。几天前开始使用 Python。

【问题讨论】:

  • \ 是一个转义序列。将 \ 更改为 \\
  • 谢谢!现在好了

标签: python file


【解决方案1】:

你最好使用os.path.join()函数

import os.path
path = os.getenv('APPDATA')
file = os.path.join(path,'keys.txt')

【讨论】:

  • @Evans - 使用os.path.join 的一个优点是它可以跨平台移植,这意味着您(开发人员)无需担心使用哪个路径分隔符,也无需转义。这是一个可靠、强大的解决方案。
猜你喜欢
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
相关资源
最近更新 更多