2014-10-19 109 views
-6
import shutil 
import getpass 
u=getpass.getuser() # This is getting the users username for the later line 

autosave="" 
print("Welcome to my Beta Text Editor") 
a=input("Would you like to make a new document? Y/N: ") 
if a=="Y": 
    nf=open("newfile.txt","w") 
    nf.close() 
    fs=input("Where would you like to put the file (Enter the Location Link") 
    if fs is not "": 
     shutil.copy2(nf, fs) 
    elif fs is "": 
     shutil.copy2(nf, "C:\Users\"+u+'\Desktop') 
     # This is combining the location with the username the line above ^^^ 
+2

那麼最新的問題? – Kasramvd 2014-10-19 10:35:54

+1

@Kasra:我的猜測:在'\「' – 2014-10-19 10:36:35

+0

不Python中發出任何超過‘發生錯誤,請重新輸入密碼’ – usr2564301 2014-10-19 10:37:24

回答

2

在Python中的反斜線轉義下一個字符。你逃過了",所以你沒有關閉字符串。

雙反斜線:

shutil.copy2(nf, "C:\\Users\\"+u+'\\Desktop') 

更妙的是,使用os.path.join()構建路徑:

shutil.copy2(nf, os.path.join("C:\\Users", u, 'Desktop')) 

注意,我還是逃了出來反斜線路徑的第一部分。您可以使用原始字符串字面避免:

shutil.copy2(nf, os.path.join(r"C:\Users", u, 'Desktop')) 

但要注意,即使是原始字符串字面量不能在一個反斜線結束。

請注意,shutil.copy2()需要兩個文件名,而不是一個打開的文件對象!通過在nf,而不是文件對象本身:

shutil.copy2(nf.name, os.path.join(r"C:\Users", u, 'Desktop')) 

其中FileIO.name attribute是文件對象的文件名。

+0

它的工作原理,但我仍然得到這個錯誤:'回溯(最近通話最後一個) : 文件 「C:\用戶\用戶\桌面\文本編輯器測試版的.py!」,14號線在 shutil.copy2(NF,os.path.join( 「C:\\用戶」,U, '桌面')) 類型錯誤:類型的對象_io.TextIOWrapper'沒有LEN()' – 2014-10-19 20:29:12

+0

續:'文件 「C:\ Program Files文件\ Python3.4.1 \ LIB \ shutil.py」,線路243,在COPY2 DST = os.path.join(DST,os.path.basename(SRC)) 文件 「C:\ Program Files文件\ Python3.4.1 \ lib中\ ntpath.py」,管線246,在基名 返回分裂(對)[1] 文件 「C:\ Program Files文件\ Python3.4.1 \ lib中\ ntpath.py」,線217,在分割 d,p = splitdrive(p) 文件「C:\ Program Files文件\ Python3.4.1 \ lib \ ntpath.py「,第159行,分割驅動器 如果len(p)> 1:' – 2014-10-19 20:30:00

+0

@JosephSenior:當文件*名稱*爲預期時,您傳入*文件對象*。 – 2014-10-19 20:33:30