1price = 33.3
2with open("Output.txt", "w") as text_file:
3 text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
1# Program to read entire file
2import os
3PATH = "H:\\py_learning\\interviewsprep"
4os.chdir(PATH)
5def file_read(fname,mode='r+'):
6 try:
7 with open(fname) as txt:
8 print(txt.read())
9 print('>>>>>>>>>>>>>>>')
10 except FileNotFoundError:
11 print("check file existance in current working directory i.e : ",os.getcwd())
12 print('provide file existance path to PATH variable')
13 finally:
14 pass
15file_read('file1.txt')
16
1#for reading and writing data in a text file with python
2#First you must have a file Open or create a new file have it loaded in memory.
3# Open function to open the file "MyFile1.txt"
4# (same directory) in append mode and
5file1 = open("MyFile.txt","a")
6
7# store its reference in the variable file1
8# and "MyFile2.txt" in D:\Text in file2
9file2 = open(r"D:\Text\MyFile2.txt","w+")
10
11# Opening and Closing a file "MyFile.txt"
12# for object name file1.
13file1 = open("MyFile.txt","a")
14file1.close()
15
16# Program to show various ways to read and
17# write data in a file.
18file1 = open("myfile.txt","w")
19L = ["This is Delhi \n","This is Paris \n","This is London \n"]
20
21# \n is placed to indicate EOL (End of Line)
22file1.write("Hello \n")
23file1.writelines(L)
24file1.close() #to change file access modes
25
26file1 = open("myfile.txt","r+")
27
28print "Output of Read function is "
29print file1.read()
30print
31
32# seek(n) takes the file handle to the nth
33# bite from the beginning.
34file1.seek(0)
35
36print "Output of Readline function is "
37print file1.readline()
38print
39
40file1.seek(0)
41
42# To show difference between read and readline
43print "Output of Read(9) function is "
44print file1.read(9)
45print
46
47file1.seek(0)
48
49print "Output of Readline(9) function is "
50print file1.readline(9)
51
52file1.seek(0)
53# readlines function
54print "Output of Readlines function is "
55print file1.readlines()
56print
57file1.close()
58
59# Python program to illustrate
60# Append vs write mode
61file1 = open("myfile.txt","w")
62L = ["This is Delhi \n","This is Paris \n","This is London \n"]
63file1.close()
64
65# Append-adds at last
66file1 = open("myfile.txt","a")#append mode
67file1.write("Today \n")
68file1.close()
69
70file1 = open("myfile.txt","r")
71print "Output of Readlines after appending"
72print file1.readlines()
73print
74file1.close()
75
76# Write-Overwrites
77file1 = open("myfile.txt","w")#write mode
78file1.write("Tomorrow \n")
79file1.close()
80
81file1 = open("myfile.txt","r")
82print "Output of Readlines after writing"
83print file1.readlines()
84print
85file1.close()
86
87Output of Readlines after appending
88['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
89
90Output of Readlines after writing
91['Tomorrow \n']