Multi-paragraph in a text creator

This is the place for queries that don't fit in any of the other categories.

Multi-paragraph in a text creator

Postby khadis » Wed Feb 13, 2013 9:25 am

Hello,
I am trying to create a flat text creator while I am doing my self-study. I know how to make user can type in my application, but it's only for one or two paragraphs. How to make user can type more paragraph in my application?

Code: Select all
jawab = "y"
while jawab == "y":
   print ".:PYTHON FLAT TEXT CREATOR v.01:."

   print "Apa yang ingin Anda lakukan?"
   print "'n' Buat file baru"
   print "'o' Buka file terdahulu"
   print "'c' Copy file terdahulu"
   print "'q' Tutup aplikasi"

   pilih_menu = raw_input("> ")
   if pilih_menu == 'n':
      print "Masukkan nama file yang hendak dibuat beserta ekstensinya (.doc atau .txt)."
      filename = raw_input("> ")
      target = open(filename, 'w')
      tulis = raw_input("Tulis di bawah: \n")
      target.write(tulis + "\n")
      tulis = raw_input("\n")
      target.write(tulis + "\n")
      target.close()
      print "\n"
      print "File berhasil dibuat."
      print "\n"
   elif pilih_menu == 'o':
      print "Masukkan nama file yang ingin dibuka: "
      filename = raw_input("> ")
      target = open(filename, 'r')
      print target.read()
      print "\n"
   elif pilih_menu == 'c':
      file_to_copy = raw_input("file yang akan di-copy: ")
      file_to_paste = raw_input("hasil copy-an: ")

      in_file = open (file_to_copy)
      in_data = in_file.read()

      print "'l' Lanjutkan"
      print "'b' Batalkan"

      pilihan = raw_input("> ")
      if pilihan == 'l':
         out_file = open (file_to_paste, 'w')
         out_file.write(in_data)
         print "Peng-copy-an berhasil."
         out_file.close()
         in_file.close()
         print "\n"
      elif pilihan == 'b':
         print "Peng-copy-an dibatalkan."
         print "\n"
   elif pilih_menu == 'q':
                print "Terima kasih telah menggunakan PYTHON FLAT TEXT CREATOR v.01"
      exit()
        else:
            print "Pilih sesuai kode yang tersedia!"
            print "\n"

khadis
 
Posts: 4
Joined: Wed Feb 13, 2013 8:59 am

Re: Multi-paragraph in a text creator

Postby stranac » Wed Feb 13, 2013 11:37 am

Hello!

Could you please translate your code to english?

One of the greatest advantages of python is it's readability, and code being obvious at a glance.
And it's really hard to read code in a foreign language.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 886
Joined: Thu Feb 07, 2013 3:42 pm

Re: Multi-paragraph in a text creator

Postby khadis » Wed Feb 13, 2013 1:31 pm

Hello,
I am sorry for my fault, to post my own language :D and here are the new scripts:

Code: Select all
answer = "y"
while answer == "y":
   print ".:PYTHON FLAT TEXT CREATOR v.01:."

   print "What do you want to do?"
   print "'n' Create new file"
   print "'o' Open a file"
   print "'c' Copy a file"
   print "'q' Close application"

   choose_menu = raw_input("> ")
   if choose_menu == 'n':
      print "Type the file name and its extension (.doc atau .txt)."
      filename = raw_input("> ")
      target = open(filename, 'w')
      write_text = raw_input("Write your text here: \n")
      target.write(write_text + "\n")
      write_text = raw_input("\n")
      target.write(write_text + "\n")
      target.close()
      print "\n"
      print "File created."
      print "\n"
   elif choose_menu == 'o':
      print "Enter a file name to open: "
      filename = raw_input("> ")
      target = open(filename, 'r')
      print target.read()
      print "\n"
   elif choose_menu == 'c':
      file_to_copy = raw_input("Name of file to be copied: ")
      file_to_paste = raw_input("Name of copied file would be: ")

      in_file = open (file_to_copy)
      in_data = in_file.read()

      print "'l' Continue"
      print "'b' Abort"

      choose = raw_input("> ")
      if choose == 'l':
         out_file = open (file_to_paste, 'w')
         out_file.write(in_data)
         print "Copying success."
         out_file.close()
         in_file.close()
         print "\n"
      elif choose == 'b':
         print "Copying aborted."
         print "\n"
   elif choose_menu == 'q':
      print "Thanks for using PYTHON FLAT TEXT CREATOR v.01"
      exit()
   else:
       print "Please choose available codes!"
       print "\n"

khadis
 
Posts: 4
Joined: Wed Feb 13, 2013 8:59 am

Re: Multi-paragraph in a text creator

Postby Mekire » Wed Feb 13, 2013 1:33 pm

This amused me a bit so I took a shot. I speak no Indonesian whatsoever.
The simple answer to your question is you need to use a while loop.
Code: Select all
filename = raw_input("> ")
with open(filename,'w') as myfile:
    myline = 1
    while myline:
        myline = raw_input("Input line (enter to finish): \n")
        myfile.write(myline+"\n")


I find the most challenging thing with these projects that include endless types of user inputs is making the code clean; as opposed to a chaotic stream of consciousness.

Here is my shot at that. It could still be cleaned up even more so. I will leave it to you to translate back into your own language. :P
Code: Select all
class FileOps:
    def __init__(self):
        print(".:PYTHON FLAT TEXT CREATOR v.01:.")
        self.run = 1
        self.main_menu = {'n':("Create new file",self.new_file),
                          'r':("Read an existing file",self.read_file),
                          'c':("Copy contents of an existing file",self.copy_file),
                          'q':("Quit",self.quit_prog)}
    def main(self):
        while self.run:
            print ("What would you like to do?")
            for opt in 'nrcq':
                print("[{}]: {}".format(opt,self.main_menu[opt][0]))
            menu_select = ""
            while menu_select not in ("n","r","c","q"):
                print("Please select from the above menu.")
                menu_select = raw_input("> ").lower()
            self.main_menu[menu_select][1]()

    def new_file(self):
        print("Please enter you desired file name including extension (.doc atau .txt).")
        filename = raw_input("> ")
        with open(filename,'w') as myfile:
            myline = 1
            while myline:
                myline = raw_input("Input line (enter to finish): \n")
                myfile.write(myline+"\n")
        print("\nFile written successfully.\n")

    def read_file(self):
        go = 1
        while go:
            print("What file would you like to read?")
            filename = raw_input("> ")
            try:
                with open(filename,'r') as myfile:
                    print(myfile.read()+"\n")
                    go = 0
            except IOError:
                print("Sorry. File not found.")

    def copy_file(self):
        go = 1
        while go:
            file_to_copy = raw_input("Enter the name of the file you wish to copy: ")
            try:
                with open(file_to_copy,'r') as copyfile:
                    in_data = copyfile.read()
                    go = 0
            except IOError:
                print("Sorry. File not found.")

        file_to_paste = raw_input("Enter target file name (existing files may be overwritten): ")
        print("[c]: Continue")
        print("[a]: Abort")

        go = ""
        while go not in ("c","a"):
            print("Confirm file copy?")
            go = raw_input("> ").lower()
        if go == 'c':
            with open(file_to_paste,"w") as pastefile:
                pastefile.write(in_data)
                print("Copy completed successfully.\n")
        elif go == 'a':
            print("Copy aborted.\n")

    def quit_prog(self):
        print("\nThank you for using PYTHON FLAT TEXT CREATOR v.01")
        self.run = 0

###
if __name__ == "__main__":
    MyOps = FileOps()
    MyOps.main()
       


Have fun,
-Mek
User avatar
Mekire
 
Posts: 816
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Multi-paragraph in a text creator

Postby stranac » Wed Feb 13, 2013 2:17 pm

Just a few additional notes:
  • You should always close your files. A good way to be certain a file will be close it to use the with statement. This will automatically close the file, even if there's an error later in your program.
    Code: Select all
    with open(filename) as f:
        # do stuff with f
  • It is a convention(a pretty strong one) to use 4 spaces to indent python code.
  • You shouldn't use exit(). It only exists as an implementation detail(so it's not even guaranteed to exist in different python implementations), and it's only meant to be used in the interpreter, as a convenience function. You should use sys.exit() instead(or you could just use break in your case).
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 886
Joined: Thu Feb 07, 2013 3:42 pm

Re: Multi-paragraph in a text creator

Postby khadis » Thu Feb 14, 2013 3:14 am

Thanks for the help. Actually, I've just started learning python in recent 2 moths and still try to grasp "the pattern" of the scripts :D
The code you all given to me is actually still to far from my "logic". But it was great, because it made me learn something new. The soon I got problem, I'll be asking more :D
khadis
 
Posts: 4
Joined: Wed Feb 13, 2013 8:59 am

Re: Multi-paragraph in a text creator

Postby Mekire » Thu Feb 14, 2013 4:31 am

As I said, your code is very much a stream of consciousness. This is quite common with beginning programmers. The first thing you should ask yourself is, "How can I break my code down into simpler building blocks?" The simple answer in this case is functions. There are certain separate tasks you wish to perform; Create a new file, Read an existing file, copy a file, and quit. To improve organization you should make each of these separate tasks its own function. If you haven't tackled writing functions yet, then that should be your primary objective right now.

It is very common to see people who have just started learning python, rush to create their first "game". Usually these consist of endless amounts of raw_inputs and no organization whatsoever. Those who take the time to grasp functions; and then move on to tackle classes are those who will have the most success.

-Mek
User avatar
Mekire
 
Posts: 816
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 3 guests