How to write to text file in python?How can I represent an 'Enum' in Python?How to flush output of print function?How do I use raw_input in Python 3Way to create multiline comments in Python?What is the Python 3 equivalent of “python -m SimpleHTTPServer”Using Python 3 in virtualenvHow can I save output tho the same file that I have got the data from, in Python 3Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?python generate fixed size (16 bytes) real random stringpython asyncronous images download (multiple urls)

What does it mean to count a group of numbers with their multiplicity?

What quests do you need to stop at before you make an enemy of a faction for each faction?

What's this constructed number's starter?

How does the UK House of Commons think they can prolong the deadline of Brexit?

Opportunity profits vs. opportunity costs

SQL Always On COPY ONLY backups - what's the point if I cant restore the AG from these backups?

Is the interior of a Bag of Holding actually an extradimensional space?

Book where main character comes out of stasis bubble

How quickly would a wooden treasure chest rot?

Does the Giant Toad's Swallow acid damage take effect only at the start of its next turn?

Project Euler Problem 45

Why Is Sojdlg123aljg a Common Password?

Examples where "thin + thin = nice and thick"

How do I anonymously report the Establishment Clause being broken?

French equivalent of "my cup of tea"

Types of tablet... a tablet secretion

What is the name for quantum gates that can be reversed?

Where on Earth is it easiest to survive in the wilderness?

Translate English to Pig Latin | PIG_LATIN.PY

Draw the ☣ (Biohazard Symbol)

Global variables and information security

If I have an accident, should I file a claim with my car insurance company?

Why does 8 bit truecolor use only 2 bits for blue?

Was the lunar landing site always in the same plane as the CM's orbit?



How to write to text file in python?


How can I represent an 'Enum' in Python?How to flush output of print function?How do I use raw_input in Python 3Way to create multiline comments in Python?What is the Python 3 equivalent of “python -m SimpleHTTPServer”Using Python 3 in virtualenvHow can I save output tho the same file that I have got the data from, in Python 3Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?python generate fixed size (16 bytes) real random stringpython asyncronous images download (multiple urls)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am a beginner in using python. I have created a plain text file and have to encrypt it to output file. But I am getting an error as below and unable to write it to output file. The code is running but the output file which should be encrypted is created.



#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
with open(file, 'rb') as f:
content = f.read()
return content

def writefile_binary(file, content):
with open(file, 'wb') as f:
f.write(content)

def main():
parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
parser.add_argument('-in', dest = 'input', required = True)
parser.add_argument('-out', dest = 'output', required = True)
parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
args = parser.parse_args()

input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)

if __name__ == "__main__":
main()


The output file should be encrypted and it should be available in the directory.










share|improve this question


























  • What is the error that you are getting?

    – tshimkus
    Mar 28 at 4:44






  • 1





    check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

    – Deepak Garud
    Mar 28 at 4:58

















0















I am a beginner in using python. I have created a plain text file and have to encrypt it to output file. But I am getting an error as below and unable to write it to output file. The code is running but the output file which should be encrypted is created.



#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
with open(file, 'rb') as f:
content = f.read()
return content

def writefile_binary(file, content):
with open(file, 'wb') as f:
f.write(content)

def main():
parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
parser.add_argument('-in', dest = 'input', required = True)
parser.add_argument('-out', dest = 'output', required = True)
parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
args = parser.parse_args()

input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)

if __name__ == "__main__":
main()


The output file should be encrypted and it should be available in the directory.










share|improve this question


























  • What is the error that you are getting?

    – tshimkus
    Mar 28 at 4:44






  • 1





    check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

    – Deepak Garud
    Mar 28 at 4:58













0












0








0








I am a beginner in using python. I have created a plain text file and have to encrypt it to output file. But I am getting an error as below and unable to write it to output file. The code is running but the output file which should be encrypted is created.



#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
with open(file, 'rb') as f:
content = f.read()
return content

def writefile_binary(file, content):
with open(file, 'wb') as f:
f.write(content)

def main():
parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
parser.add_argument('-in', dest = 'input', required = True)
parser.add_argument('-out', dest = 'output', required = True)
parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
args = parser.parse_args()

input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)

if __name__ == "__main__":
main()


The output file should be encrypted and it should be available in the directory.










share|improve this question
















I am a beginner in using python. I have created a plain text file and have to encrypt it to output file. But I am getting an error as below and unable to write it to output file. The code is running but the output file which should be encrypted is created.



#!/usr/bin/env python3
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import argparse

def readfile_binary(file):
with open(file, 'rb') as f:
content = f.read()
return content

def writefile_binary(file, content):
with open(file, 'wb') as f:
f.write(content)

def main():
parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
parser.add_argument('-in', dest = 'input', required = True)
parser.add_argument('-out', dest = 'output', required = True)
parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
args = parser.parse_args()

input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)

if __name__ == "__main__":
main()


The output file should be encrypted and it should be available in the directory.







python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 4:51









jkdev

5,8836 gold badges39 silver badges69 bronze badges




5,8836 gold badges39 silver badges69 bronze badges










asked Mar 28 at 4:32









solvig krugersolvig kruger

33 bronze badges




33 bronze badges















  • What is the error that you are getting?

    – tshimkus
    Mar 28 at 4:44






  • 1





    check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

    – Deepak Garud
    Mar 28 at 4:58

















  • What is the error that you are getting?

    – tshimkus
    Mar 28 at 4:44






  • 1





    check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

    – Deepak Garud
    Mar 28 at 4:58
















What is the error that you are getting?

– tshimkus
Mar 28 at 4:44





What is the error that you are getting?

– tshimkus
Mar 28 at 4:44




1




1





check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

– Deepak Garud
Mar 28 at 4:58





check your formatting. Below a function or if condition etc, there should be 4 spaces or a tab. If this is not consistent, your code may not be called.

– Deepak Garud
Mar 28 at 4:58












2 Answers
2






active

oldest

votes


















0
















These two lines:



input_content = readfile_binary(args. input)
output_content = writefile_binary(args. output)


There should not be a space in args.input. Here is an example,



import argparse

parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()

# using type hints can help reasoning about code
def write(filename: str, content: str) -> None:
with open(filename, 'wb') as f:
f.write(str.encode(content))

# if the filename was successfully parsed from stdin
if args.filename == 'filename.txt':
print(f"args: args.filename")

# write to the appropriate output file
write(filename=args.filename, content="content")





share|improve this answer
































    0
















    You might need to correct your code's indentation. Python requires indenting code within each function definition, loop, etc.



    And as eric points out, there should be no spaces after the periods in args. input and args. output. Change those to args.input and args.output instead.



    So:



    #!/usr/bin/env python3
    import os
    import binascii
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.primitives import padding
    from cryptography.hazmat.backends import default_backend
    import argparse

    def readfile_binary(file):
    with open(file, 'rb') as f:
    content = f.read()
    return content

    def writefile_binary(file, content):
    with open(file, 'wb') as f:
    f.write(content)

    def main():
    parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
    parser.add_argument('-in', dest = 'input', required = True)
    parser.add_argument('-out', dest = 'output', required = True)
    parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
    parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
    args = parser.parse_args()

    input_content = readfile_binary(args.input)
    output_content = writefile_binary(args.output)

    if __name__ == "__main__":
    main()





    share|improve this answer





























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );














      draft saved

      draft discarded
















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390212%2fhow-to-write-to-text-file-in-python%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0
















      These two lines:



      input_content = readfile_binary(args. input)
      output_content = writefile_binary(args. output)


      There should not be a space in args.input. Here is an example,



      import argparse

      parser = argparse.ArgumentParser()
      parser.add_argument('filename')
      args = parser.parse_args()

      # using type hints can help reasoning about code
      def write(filename: str, content: str) -> None:
      with open(filename, 'wb') as f:
      f.write(str.encode(content))

      # if the filename was successfully parsed from stdin
      if args.filename == 'filename.txt':
      print(f"args: args.filename")

      # write to the appropriate output file
      write(filename=args.filename, content="content")





      share|improve this answer





























        0
















        These two lines:



        input_content = readfile_binary(args. input)
        output_content = writefile_binary(args. output)


        There should not be a space in args.input. Here is an example,



        import argparse

        parser = argparse.ArgumentParser()
        parser.add_argument('filename')
        args = parser.parse_args()

        # using type hints can help reasoning about code
        def write(filename: str, content: str) -> None:
        with open(filename, 'wb') as f:
        f.write(str.encode(content))

        # if the filename was successfully parsed from stdin
        if args.filename == 'filename.txt':
        print(f"args: args.filename")

        # write to the appropriate output file
        write(filename=args.filename, content="content")





        share|improve this answer



























          0














          0










          0









          These two lines:



          input_content = readfile_binary(args. input)
          output_content = writefile_binary(args. output)


          There should not be a space in args.input. Here is an example,



          import argparse

          parser = argparse.ArgumentParser()
          parser.add_argument('filename')
          args = parser.parse_args()

          # using type hints can help reasoning about code
          def write(filename: str, content: str) -> None:
          with open(filename, 'wb') as f:
          f.write(str.encode(content))

          # if the filename was successfully parsed from stdin
          if args.filename == 'filename.txt':
          print(f"args: args.filename")

          # write to the appropriate output file
          write(filename=args.filename, content="content")





          share|improve this answer













          These two lines:



          input_content = readfile_binary(args. input)
          output_content = writefile_binary(args. output)


          There should not be a space in args.input. Here is an example,



          import argparse

          parser = argparse.ArgumentParser()
          parser.add_argument('filename')
          args = parser.parse_args()

          # using type hints can help reasoning about code
          def write(filename: str, content: str) -> None:
          with open(filename, 'wb') as f:
          f.write(str.encode(content))

          # if the filename was successfully parsed from stdin
          if args.filename == 'filename.txt':
          print(f"args: args.filename")

          # write to the appropriate output file
          write(filename=args.filename, content="content")






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 5:05









          ericeric

          6111 gold badge3 silver badges8 bronze badges




          6111 gold badge3 silver badges8 bronze badges


























              0
















              You might need to correct your code's indentation. Python requires indenting code within each function definition, loop, etc.



              And as eric points out, there should be no spaces after the periods in args. input and args. output. Change those to args.input and args.output instead.



              So:



              #!/usr/bin/env python3
              import os
              import binascii
              from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
              from cryptography.hazmat.primitives import padding
              from cryptography.hazmat.backends import default_backend
              import argparse

              def readfile_binary(file):
              with open(file, 'rb') as f:
              content = f.read()
              return content

              def writefile_binary(file, content):
              with open(file, 'wb') as f:
              f.write(content)

              def main():
              parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
              parser.add_argument('-in', dest = 'input', required = True)
              parser.add_argument('-out', dest = 'output', required = True)
              parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
              parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
              args = parser.parse_args()

              input_content = readfile_binary(args.input)
              output_content = writefile_binary(args.output)

              if __name__ == "__main__":
              main()





              share|improve this answer































                0
















                You might need to correct your code's indentation. Python requires indenting code within each function definition, loop, etc.



                And as eric points out, there should be no spaces after the periods in args. input and args. output. Change those to args.input and args.output instead.



                So:



                #!/usr/bin/env python3
                import os
                import binascii
                from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
                from cryptography.hazmat.primitives import padding
                from cryptography.hazmat.backends import default_backend
                import argparse

                def readfile_binary(file):
                with open(file, 'rb') as f:
                content = f.read()
                return content

                def writefile_binary(file, content):
                with open(file, 'wb') as f:
                f.write(content)

                def main():
                parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
                parser.add_argument('-in', dest = 'input', required = True)
                parser.add_argument('-out', dest = 'output', required = True)
                parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
                parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
                args = parser.parse_args()

                input_content = readfile_binary(args.input)
                output_content = writefile_binary(args.output)

                if __name__ == "__main__":
                main()





                share|improve this answer





























                  0














                  0










                  0









                  You might need to correct your code's indentation. Python requires indenting code within each function definition, loop, etc.



                  And as eric points out, there should be no spaces after the periods in args. input and args. output. Change those to args.input and args.output instead.



                  So:



                  #!/usr/bin/env python3
                  import os
                  import binascii
                  from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
                  from cryptography.hazmat.primitives import padding
                  from cryptography.hazmat.backends import default_backend
                  import argparse

                  def readfile_binary(file):
                  with open(file, 'rb') as f:
                  content = f.read()
                  return content

                  def writefile_binary(file, content):
                  with open(file, 'wb') as f:
                  f.write(content)

                  def main():
                  parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
                  parser.add_argument('-in', dest = 'input', required = True)
                  parser.add_argument('-out', dest = 'output', required = True)
                  parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
                  parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
                  args = parser.parse_args()

                  input_content = readfile_binary(args.input)
                  output_content = writefile_binary(args.output)

                  if __name__ == "__main__":
                  main()





                  share|improve this answer















                  You might need to correct your code's indentation. Python requires indenting code within each function definition, loop, etc.



                  And as eric points out, there should be no spaces after the periods in args. input and args. output. Change those to args.input and args.output instead.



                  So:



                  #!/usr/bin/env python3
                  import os
                  import binascii
                  from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
                  from cryptography.hazmat.primitives import padding
                  from cryptography.hazmat.backends import default_backend
                  import argparse

                  def readfile_binary(file):
                  with open(file, 'rb') as f:
                  content = f.read()
                  return content

                  def writefile_binary(file, content):
                  with open(file, 'wb') as f:
                  f.write(content)

                  def main():
                  parser = argparse.ArgumentParser(description = 'Encryption and Decryption of the file')
                  parser.add_argument('-in', dest = 'input', required = True)
                  parser.add_argument('-out', dest = 'output', required = True)
                  parser.add_argument('-K', dest = 'key', help = 'The key to be used for encryption must be in hex')
                  parser.add_argument('-iv', dest = 'iv', help = 'The inintialisation vector, must be in hex')
                  args = parser.parse_args()

                  input_content = readfile_binary(args.input)
                  output_content = writefile_binary(args.output)

                  if __name__ == "__main__":
                  main()






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 2 at 19:18

























                  answered Mar 28 at 4:58









                  jkdevjkdev

                  5,8836 gold badges39 silver badges69 bronze badges




                  5,8836 gold badges39 silver badges69 bronze badges































                      draft saved

                      draft discarded















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390212%2fhow-to-write-to-text-file-in-python%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현