2017-03-05 13 views
-1

.txtまたは.datファイルを作成するプログラムを作成しようとしています(ユーザーの選択に依存します)。その後、別の値に変換されます。.datファイルを作成し、ランダムなASCII値を書き込んでその文字形式に変換する

ランダムな文字が指定されている場合、これは対応するASCII値に変換する必要があり、その逆もあります。プログラムの

import random # import randomdeals with random generation 
import string # import string contains sequences of common ASCII characters 

userInput = input("Which file would you like to open either a .txt file or a .dat file?") # let the user decide which file type they want to open 

def randomCharacter(): 
    return random.choice(string.ascii_letters) 
def randomASCII(): 
    return random.randint(97,122) 

if userInput == (".txt"): 
    with open("characterConversion.txt", "w") as textFile: 
     textFile.write(randomCharacter()) 
     textFile.close() 
    textFile = open("characterConversion.txt", "r+") 
    character = textFile.readline(1) 
    textFile.write("\n converted into its ASCII value is \n") #/n means a new line 
    textFile.write(str(ord(character))) 
    textFile.close() 
if userInput == (".dat"): 
    with open("asciiConversion.dat", "w") as datFile: 
     datFile.write(str(randomASCII())) 
     datFile.close() 
    datFile = open("asciiConversion.dat", "r+") 
    ascii = int(datFile.readline(1)) 
    character = chr(randomASCII()) 
    datFile.write(str(ascii)) 
    datFile.write("\n in its character form is \n") 
    datFile.write(character) 
    datFile.close() 

マイ.txtの部分は、私はそれを修正するが、私は今、私の.datファイルとのトラブルを抱えています助けた以前のユーザーに大きな感謝を作品:

は、現時点ではこれは私が持っているものです。私は.datのように私の入力を入力すると、読み込むファイル開いた後:その文字の形が数字(この場合には、それは1061年ですが)だけなので、私は97と122の間でなければなりませんしかし

あるにを私がどこに間違っているのか分からない。私ははっきり

答えて

0

を私の問題を説明していない場合、私はあなたがそれ

textFile.write(str(randomCharacter())) 
textFile.close() 
+0

OMGを変換する値の交流だったとして、私は2つの異なるASCII値を書いていたように、第2 datFile.writeを削除しましたが、私ときファイルを閉じた後にファイルを開きます。 Ben

+0

関数呼び出し '()'がありません。 –

1

は、あなたが文字列にrandomCharacterという名前の関数を変換str(randomCharacter)を行う上で書き込んだ後に開かれたファイルをクローズする必要が謝罪、しかし、あなたは呼び出すことはありませんそれ。

渡すパラメータがない場合でも、あるいは意味が異なる場合でも、Pythonでは括弧を入れなければなりません。

あなたがそれを呼び出したとしても、結果は返されません(VBを使ってPythonコードをひねったように見えます)。だから、/フラッシュ閉じられた後、ファイルを確実にするためにwithコンテキストブロックを使用し

def randomCharacter(): 
    return random.choice(string.ascii_letters) 

の操作を行います。

if userInput == ".txt": 
    with open("characterConversion.txt", "w") as textFile: 
     textFile.write(randomCharacter()) 
0

あなたはどこでもrandomCharacter機能で作成したランダムな文字を保存していません。それ以外にも、このランダムに作成された文字の代わりに、関数自体を返しています。

これは動作します:randomCharacterによって返された値がすでに文字列であるため、

userInput = input("Which file would you like to open either a .txt file or a .dat file? ") 

def randomCharacter(): 
    random_character = random.choice(string.ascii_letters) 
    return random_character 

if userInput == ".txt": 
    with open("characterConversion.txt", "w") as f: 
     f.write(randomCharacter()) 

はまた、あなたが、ここstr機能を使用する必要はありません。私が行うために必要な何

0

プログラムは、私はそれを行うのを忘れて、私は信じることができない

関連する問題