Python PART - 5 !!


Here we will learn use of
1) \\
2) \t
3) \t*





Now let us move to another part of Python which is quite important. v
To run a file by the script of another file.
Make a file, let it be a.py
Write the contents of file.
Let the contents be:
Hello, today is a sunny day.
Now make another file to write script, let it be b.py and its script be :

from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)
print txt_again.read()
print "script is " script
Now go to terminal and type :
python b.py a.py

Here , txt = open(filename) makes a 'file object' through which we can access file.




close -- Closes the file. Like File->Save.. in your editor.
read -- Reads the contents of the file. You can assign the result to a variable.
readline -- Reads just one line of a text file.
truncate -- Empties the file. Watch out if you care about the file.
write('stuff') -- Writes "stuff" to the file.


Now let us use these.

open c.py and write its contents :

from sys import argv
script, filename = argv
print "hello, my name is %r " %filename
a = raw_input("what is your name")
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for line"
line1 = raw_input("line 1: ")
target.write(line1)
print "And we close it."
target.close()





If you use 'w' then you're saying "open this file in 'write' mode," thus the 'w' character. There's also 'r' for "read," 'a' for append, and modifiers on these.
open(filename) open it in 'r' (read) mode

No comments:

Post a Comment

SAY HELLO!!