Example 1: python writing to text file
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
Example 2: python read file
with open("file.txt", "r") as txt_file:
return txt_file.readlines()
Example 3: python read file
with open('/path/to/filename.extension', 'open_mode') as filename:
file_data = filename.readlines()
import csv
with open('/path/to/filename.extension', 'open_mode') as filename:
file_data = csv.reader(filename, delimiter='delimiter')
data_as_list = list(file_data)
import numpy as np
data = np.loadtxt('/path/to/filename.extension',
delimiter=',',
skiprows=2,
usecols=[0,2],
dtype=str)
import pandas as pd
data = pd.read_csv('/path/to/filename.extension',
nrows=5,
header=None,
sep='\t',
comment='#',
na_values=[""])
Example 4: python write file
with open("file.txt", "w") as file:
for line in ["hello", "world"]:
file.write(line)
Example 5: reading and writing data in a text file with python
file1 = open("MyFile.txt","a")
file2 = open(r"D:\Text\MyFile2.txt","w+")
file1 = open("MyFile.txt","a")
file1.close()
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close()
file1 = open("myfile.txt","r+")
print "Output of Read function is "
print file1.read()
print
file1.seek(0)
print "Output of Readline function is "
print file1.readline()
print
file1.seek(0)
print "Output of Read(9) function is "
print file1.read(9)
print
file1.seek(0)
print "Output of Readline(9) function is "
print file1.readline(9)
file1.seek(0)
print "Output of Readlines function is "
print file1.readlines()
print
file1.close()
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close()
file1 = open("myfile.txt","a")
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after appending"
print file1.readlines()
print
file1.close()
file1 = open("myfile.txt","w")
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.close()
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']
Example 6: Write a Python program to read an entire text file
import os
PATH = "H:\\py_learning\\interviewsprep"
os.chdir(PATH)
def file_read(fname,mode='r+'):
try:
with open(fname) as txt:
print(txt.read())
print('>>>>>>>>>>>>>>>')
except FileNotFoundError:
print("check file existance in current working directory i.e : ",os.getcwd())
print('provide file existance path to PATH variable')
finally:
pass
file_read('file1.txt')