2016-01-28 21 views
0
def file_contents(): 
    global file_encrypt 
    encryption_file = input("What is the name of the file?") 
    file_encrypt = open(encryption_file, 'r') 
    contents = file_encrypt.read() 
    print (contents) 
    ask_sure = input("Is this the file you would like to encrypt?") 
    if ask_sure == "no": 
     the_menu() 

這部分代碼打開用戶輸入的文件,對吧?這裏沒有真正的問題。我的文件沒有長度?即使它

def key_offset(): 
    key_word = '' 
    count = 0 
    total = 0 
    while count < 8: 
     num = random.randint (33, 126) 
     letter = chr(num) 
     key_word = key_word + letter  
     count = count + 1 
     offset = ord(letter) 
     total = total + offset 
    print("Make sure you copy the key for decryption.") 
    if count == 8: 
     total = total/8 
     total = math.floor(total) 
     total = total - 32 
     print(key_word) 
     return total 

這是它計算偏移等的部分等。在這裏再次沒有問題。

def encrypting(): 
    file = file_contents() 
    total = key_offset() 
    encrypted = '' 
    character_number = 0 
    length = len(file_encrypt) 

然後這是問題出現的地方,我做了可變file_encrypt在第一個代碼塊全球化的,因此它應該工作。我曾嘗試在另一個變量file_en = file_encrypt下調用它,並在計算長度時使用了file_en,但它一直說它沒有長度......我試着問朋友和我的老師,但他們似乎無能爲力。問題是,每次我到這個部分它說file_encrypt沒有長度或我嘗試過的其他方式,file_en沒有長度,與TextWrapper.io有關。

+0

Python的'file'對象沒有一個長度。如果你想知道一個文件有多大,可以讀取所有的字節並查看它的長度,或者使用像http://stackoverflow.com/questions/2104080/how-to-check-file-大小在蟒蛇 –

+0

那麼,根據[文檔](https://docs.python.org/2/library/stdtypes.html#file-objects)文件對象沒有長度。我沒有看到任何定義'len(file_object)'應該返回的定義。從文件讀取的數據可能有長度(因爲數據將是字符串,並且定義了字符串的長度),但是文件對象沒有。 –

+0

因此,如果我更改全局和一切到文件的實際名稱,所以在這種情況下,encryption_file,將工作? –

回答

2

file_encrypt是一個文件指針,它確實沒有長度。您的文件的內容在contents中,但是這是file_contents函數的本地變量。

真的,你不應該使用全局變量;這裏沒有任何理由。相反,返回實際數據 - contents - 從file_contents,那麼你可以在調用函數中使用它。

+0

我看到了,但是我已經嘗試過了,它沒有工作,我會盡量嘗試 –

1

有你的代碼的幾個問題,但是忽略那些現在,我覺得你的主要問題是:

1)函數「file_contents」不返回任何東西,我懷疑你想返回「內容」。很難說,不知道你想用「文件」變量做什麼。

def encrypting(): 
    file = file_contents() # <-- 

2)正如其他人所說,「file_encrypt」是一個指向文件的指針,雖然這個功能,你沒有申報其作爲全球性的,因此它可能是無。

def encrypting(): 
    file = file_contents() 
    total = key_offset() 
    encrypted = '' 
    character_number = 0 
    length = len(file_encrypt) # <-- 

因此,這些修改應該給你你需要的東西:

def file_contents(): 
    global file_encrypt 
    encryption_file = input("What is the name of the file?") 
    file_encrypt = open(encryption_file, 'r') 
    contents = file_encrypt.read() 
    print (contents) 
    ask_sure = input("Is this the file you would like to encrypt?") 
    if ask_sure == "no": 
     the_menu() 
    return contents # <-- ADDED 

def encrypting(): 
    contents = file_contents() # <-- MODIFIED 
    total = key_offset() 
    encrypted = '' 
    character_number = 0 
    length = len(contents) # <-- MODIFIED 
相關問題