文章詳情頁
請教: 關于 python 反斜杠轉義的疑問
瀏覽:265日期:2022-08-19 15:17:28
問題描述
a = ’D:githubdjangosamplefoo.txt’# a為foo.txt的路徑,通過os.path生成with open(a) as f: f.write('Hello') f.close()
當我執行上面這個片段的時候,提示找不到文件:’D:githubdjangosamplefoo.txt’,我覺得應該是這種路徑分隔符在windows下沒有被正確解析,于是:
a.replace(’’,’’)#我期待的結果是把路徑轉化為 D:githubdjangosamplefoo.txt.
結果提示:
SyntaxError: EOL while scanning string literal
于是想請教一下我該怎樣正確轉義或者通過其他方法達到預期的效果呢?我試過:
a.replace(’’,r’’)a.replace(’’,’’)
依舊不行,謝謝。
問題解答
回答1:文件的名稱沒問題:’’里第一個就是escape character。你可以通過print(a)試試看。
你想用f.write的話你應該通過open(a, ’w’)把文件打開:
with open(a, ’w’) as f: f.write('Hello')
另外,你用with的話f.close()是多余的。
回答2:a = r’D:githubdjangosamplefoo.txt’
相關文章:
1. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. html5和Flash對抗是什么情況?3. docker 17.03 怎么配置 registry mirror ?4. html5 - datatables 加載不出來數據。5. 運行python程序時出現“應用程序發生異常”的內存錯誤?6. node.js - mongodb查找子對象的名稱為某個值的對象的方法7. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]8. javascript - QQ第三方登錄的問題9. spring-mvc - spring-session-redis HttpSessionListener失效10. javascript - 在 model里定義的 引用表模型時,model為undefined。
排行榜

網公網安備