TIME NOW
World current time now,
CALENDAR
Calendar monthly, yearly
login CONVERT LENGTH
login CONVERT TEMPERATURE
login DICTIONARIES, LISTS
login SCIENCE EDUCATION RELIGION
login WORK CALCULATOR
login CALCULATE LIFE

Python 3 programming language, learn python, tutorial

Previous articlePage bottomNext article  ALL TOPICS

Python 3. Input, output, files

 'r' when the file will only be read,
'w' for only writing (an existing file with the same name will be erased),
'a' opens the file for appending; any data written to the file is automatically added to the end
'r+' opens the file for both reading and writing.

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding (the default being UTF-8).

'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.

1.
f = open('workfile', 'w')

# write to file
print (f.write('This is a test\n'))
print (f.write('This is a second test\n'))

value = ('the answer', 42)
s = str(value)
f.write(s)

f = open('workfile', 'r')

# read full file
print ("1. ", f.read())
# empty reading
print ("2. ", f.read())

f = open('workfile', 'r')

# read line
print ("3. ",f.readline())
print ("4. ",f.readline())
print ("5. ",f.readline())
# no line
print ("6. ",f.readline())
print ("7. ",f.readline())

f = open('workfile', 'r')

for line in f:
  print("8. ", line, end='')

# position 
print ("\n8. " , f.tell())

1a. Two styles. When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you.
Also, with statement is not just for openning files, with is used in conjuction with context managers.
# you can use print instead of pass

def 
foo():
    f = open('a.txt','r')
    for in f:
        pass
    f.close()

def foo1():
    with open('a.txt','r') as f:
        for l in f:
            pass

foo1()
foo ()

1b. File by byte. b"" == false.
with open("myfile.txt", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)
        print (byte)

1c. Similar
with open("myfile.txt", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)
        print(byte)

1d. Similar. Lambda function
with open("myfile.txt", 'rb') as file:
    for byte in iter(lambda: file.read(1), b''):
        print (byte)

2. Error. f.tell() inside of a line-by-line iteration of a file:
with open("workfile", "r+") as f:
  for line in f:
    f.tell() #OSError

2a. Solution
with open("workfile", "r") as f:
  line = f.readline()
  while line:
    print (f.tell()) # returns the location of the next line
    # comment to get infinite loop
    line = f.readline()

3. Return. f.seek method. Infinite Loop.
with open('workfile', 'r') as f:
  line = f.readline()
  while line:

    print("1", f.tell(), line) #returns the location of the next line
    line = f.readline()
    print("2", f.tell(), line)
    if line.strip() == 'This is a second test':
        # Move the pointer back to the beginning of this line
        print("RETURN", f.tell())
        f.seek(f.tell() - len(line) -1)
        # Comment break, infinite loop
        break
        
# Closed automatically

4. Binary read, write to file. closed method. seek method. 

fileObject.seek(offset[, whence])
defaults to 0, which means absolute file positioning, 
1 which means seek relative to the current position
2 means seek relative to the file's end:
f = open('workfileB', 'wb')

print(f.write(b'0123456789abcdef'))

f = open('workfileB', 'rb')

# Go to the 6th byte in the file
f.seek(5)     

print
(f.read(1))

# Go to the 3rd byte before the end
f.seek(-3, 2) 

print
(f.read(1))

f.close()

print (f.closed)

f.read()

Task 1:
From /var/log/auth.log please take good and false logins; Print table, which contains logins per month and user. There must statistics for every month.  Words "False logins" and "Good logins" are centered:

             False logins:

    | root      | studentas |
----------------------------
Aug | 20        | 5         |
Sep | 10        | 2         |


            Good logins:

    | root      | studentas |
---------------------------- 
Aug | 5         | 155       |
Sep | 5000      | 10000     |

 
 
Task3:
Pasirinkimų meniu, papildyti, išvesti, ištrinti.
Papildyti įvestu vardu ir pavarde failą. Faile -CSV formatas.
Išvesti format metodo pagalba.
Trinti, nurodant eilutės numerį. 
Previous articlePage topNext article  ALL TOPICS


Uzd:
x=0
list=[]
while True:
if x==1:
f = open('file.txt','a')
fname = input("Vardas\n")
lname = input("Pavarde\n")
f.write(str(fname).rjust(20)+"   "+str(lname)+"\n")
if x==2:
f = open('file.txt','r')
print(f.read())
if x==3:
f = open('file.txt','w')
print("Sarasas tuscias")
if x==4:
f = open('file.txt','r')
print(f.read())
y=int(input("Kuria elute istrinti?\n"))
f = open('file.txt','r')
for n in f:
if n!=y:
list.append(f.readline())
f = open('file.txt','w')
for x in list:
f.write(list[x])
x=0
while x<1 or x>5:
x=int(input("Pasirinkimu menu\n1 - Papildyti\n2 - Isvesti\n3 - Istrinti viska\n4 - Istrinti eilute\n5 - Baigti\n"))
if x==5:
break


2015-11-23 10:17:03
uzd3:
module.py
def ived():
print("\n","-"*15,"Ivedimas","-"*15,"\n")
while True:
fname='Vardas'
while fname!='':
fname = input("Vardas: ")
fname=fname.replace("1","")
fname=fname.replace("2","")
fname=fname.replace("3","")
fname=fname.replace("4","")
fname=fname.replace("5","")
fname=fname.replace("6","")
fname=fname.replace("7","")
fname=fname.replace("8","")
fname=fname.replace("9","")
fname=fname.replace("0","")
if fname=='':
print("Vardas turi buti sudaritas tik is raidziu. Bandikite dar karta.")
else:
break
if fname!='':
break
while True:
lname='Pavarde'
while lname!='':
lname = input("Pavarde: ")
lname=lname.replace("1","")
lname=lname.replace("2","")
lname=lname.replace("3","")
lname=lname.replace("4","")
lname=lname.replace("5","")
lname=lname.replace("6","")
lname=lname.replace("7","")
lname=lname.replace("8","")
lname=lname.replace("9","")
lname=lname.replace("0","")
if lname=='':
print("Pavarde turi buti sudaritas tik is raidziu. Bandikite dar karta.")
else:
break
if lname!='':
break
f = open('file.txt','a')
f.write("\""+fname+"\";\""+lname+"\";\n")
print("\nPapildyta!")
def spaus():
print("\n","-"*15,"Failo turinys","-"*15,"\n")
f = open('file.txt','r')
print(str("Vardas").ljust(15),"Pavarde\n","-"*30)
n=1
while True:
string = f.readline()
if string!="":
list=string.split(';',1)
list[0]=list[0].replace("\"","")
list[0]=list[0].replace(";","")
list[1]=list[1].replace("\"","")
list[1]=list[1].replace(";","")
list[1]=list[1].replace("\n","")
print(n,"-",str(list[0]).ljust(15),list[1])
n+=1
else:
break
def trin():
f = open('file.txt','w')
print("\n","-"*15,"Sarasas tuscias","-"*15,"\n")

def eiltrin():
list=[]
f = open('file.txt','r')
while True:
string = f.readline()
if string!="":
list.append(string)
else:
break
y=0
while True:
try:
while y<1 or y>len(list):
y=int(input("Kuria eilute istrinti?  "))
except ValueError:
print("Eilutes Nr")
else:
break
f = open('file.txt','w')
for l in range(0,len(list)):
if l!=y-1:
f.write(list[l])

def menu(x):
while x<1 or x>5:
print("\n","-"*10,"Pasirinkimu menu","-"*10,"\n")
x=int(input("1 - Papildyti\n2 - Isvesti\n3 - Istrinti viska\n4 - Istrinti eilute\n5 - Baigti\n"))
return x
----------------------------------------------------------------------------------------------------------------------
import module
x=0
list=[]
while True:
if x==1:
module.ived()
if x==2:
module.spaus()
if x==3:
module.trin()
if x==4:
module.eiltrin()
x=0
x=module.menu(x)
if x==5:
break


2015-12-03 08:41:25
Guest:
Modulis tas pats
tik papildomai
def spausHTML():
    print("\n","-"*15,"HTML","-"*15,"\n")
    HTML=""
    f = open('file.txt','r')
    print(str("Vardas").ljust(15),"Pavarde\n","-"*30)
    n=1
    while True:
        string = f.readline()
        if string!="":
            list=string.split(';',1)
            list[0]=list[0].replace("\"","")
            list[0]=list[0].replace(";","")
            list[1]=list[1].replace("\"","")
            list[1]=list[1].replace(";","")
            list[1]=list[1].replace("\n","")
            HTML+="<tr><td>" + str(n) + "</td><td>" + list[0] + "</td><td>"+ list[1] + "</td></tr>\n"
            n+=1
        else:
            break
   
    HTMLfin="<html><head></head><body><h1>DUOMENYS</h1><table border = 1 >\n" + HTML + "\n</table></body></html>"
   
    f.close()
    #print (HTMLfin)
   
    fHTML = open('c:/xampp/htdocs/index.html','w')
    fHTML.write(HTMLfin)
    fHTML.close()
 
 
failas:
 
import module
x=0
list=[]
while True:
    if x==1:
        module.ived()
    if x==2:
        module.spaus()
    if x==3:
        module.trin()
    if x==4:
        module.eiltrin()
    if x==5:
        module.spausHTML()
    x=0
    x=module.menu(x)
    if x==6:
        break
 
 


2015-12-03 09:15:45

 Use username: Guest, Anonymous, Programmer






QUOTES:
Romantic love is an illusion. Most of us discover this truth at the end of a love affair or else when the sweet emotions of love lead us into marriage and then turn down their flames.
Sir Thomas More
Study the past if you would define the future.
Confucius
Certainly it is a world of scarcity. But the scarcity is not confined to iron ore and available land. The most constricting scarcities are those of character and personality.
William R Allen