Python

Python Files

Accepting input from computer:

str=input(“On what platform do you work?: “)
print(str, “is now trending”)

Read text file:
myfile=open(“C:\\Test\\mytest.txt”)
str=myfile.read()
print(str)

str1=str.split(“\n”)
print(str1)
myfile.close()

Write to text file:
mynewfile=open(“C:\\Test\\mytest1.txt”,’w’)
mynewfile.write(‘EmpID\tEmpname\n1\tA\n2\tB\n3\tC\n4\tD\n’)
mynewfile.close()

mynewfile = open(“C:\\Test\\mytest1.txt”,’w’)
mynewfile.write(“This is a test\n”)
mynewfile.close()

Append to text file:
mynewfile=open(“C:\\Test\\mytest1.txt”,’a’)
mynewfile.write(‘We are appending here’)
mynewfile.close()

Rename a file:
import os
os.rename(“C:\\Test\\mytest1.txt”,”C:\\Test\\mytest2.txt”)

Remove a file:
import os
os.remove(“C:\\Test\\mytest2.txt”)

tell() method gives the position of the cursor:
File is opened in read/write (r+) mode
In the following code the position of cursor at the start, the characters read and the position of cursor after reading are printed
mytest3.txt file has the following two lines
first line comes first
second line comes second

mynewfile = open(“C:\\Test\\mytest3.txt”,’r+’)
pos1=mynewfile.tell()
print(pos1)
str=mynewfile.read(9)
print(str)
pos2=mynewfile.tell()
print(pos2)
mynewfile.close()

output:
0
first lin
9

seek:
mynewfile = open(“C:\\Test\\mytest3.txt”,’r+’)
mynewfile.seek(11)
mynewfile.write(“always”)
mynewfile.close()

Answer:
The first line in the file will be changed to “first line alwaysfirst”

Exception handling trying to open a file which is non existent:
try:
    mynewfile = open(“C:\\Test\\mytest4.txt”,’r’,encoding=’utf-8′)
    str=mynewfile.read()
    print(str)
except:
    print(“err”)
finally:
   print(“Inside finally”)

Output:
err
Inside finally 

python and json:
lst=[‘a’,’b’,’c’]
import json
str=json.dumps(lst)
print(str)
file1 = open(“C:\\Test\\file1.txt”,’w’)
json.dump(lst,file1)
Answer: The contents of the list are transferred to file

Read csv file:
myfile=open(“C:\\Test\\test1.csv”)
str=myfile.read()
print(str)

csv reader:
import csv
with open(‘C:\\Test\\test1.csv’, newline=”) as myfile:
str1 = csv.reader(myfile)
for row in str1:
print(row)

Write to csv file:
import csv
with open(‘C:\\Test\\test2.csv’,’w’, newline=”) as myfile:
str2 = csv.writer(myfile)
str2.writerow([‘EmpID’,’EmpName’])
str2.writerow([5,’Kevin’])

csv writer:
import csv
strn=[[‘EmpID’,’EmpName’],[5,’Kevin’],[6,’Warner’]]
with open(‘C:\\Test\\test3.csv’,’w’, newline=”) as myfile:
str3 = csv.writer(myfile)
str3.writerows(strn)

import csv
strn=[[‘EmpID’,’EmpName’],[5,’Kevin’],[6,’Warner’]]
with open(‘C:\\Test\\test4.csv’,’w’, newline=”) as myfile:
str3 = csv.writer(myfile,delimiter=’|’)
str3.writerows(strn)