File handling in python code example
Example 1: python file open modes
r for reading
r+ opens for reading and writing (cannot truncate a file)
w for writing
w+ for writing and reading (can truncate a file)
rb for reading a binary file. The file pointer is placed at the beginning of the file.
rb+ reading or writing a binary file
wb+ writing a binary file
a+ opens for appending
ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
x open for exclusive creation, failing if the file already exists (Python 3)
Example 2: python write file
with open("file.txt", "w") as file:
for line in ["hello", "world"]:
file.write(line)
Example 3: command to read file in python using pandas
import panda as pd
file_csv = pd.read_csv("file path")
file_excel = pd.read_excel("file path")
file_json = pd.read_json("file path")
file_html = pd.read_html("file path")
file_localClipboard = pd.read_clipboard("file path")
file_MSExcel = pd.read_excel("file path")
file_HDF5 = pd.read_hdf("file path")
file_Feather = pd.read_feather("file path")
file_msgpack = pd.read_msgpack("file path")
file_stata = pd.read_stata("file path")
file_SAS = pd.read_sas("file path")
file_paythonPickle = pd.read_pickle("file path")
file_SQL = pd.read_sql("file path")
file_google_big_query = pd.read_gbq("file path")
Example 4: open file python
with open('filename', 'a') as f:
f.write(var1)
f.write('data')
f.close()
with open('filename', 'r') as f:
with open('filename', 'x') as f:
with open('filename', 't') as f:
with open('filename', 'b') as f:
with open('filename', 'w') as f:
with open('filename', '+') as f:
Example 5: python file open
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')
file.close()
Example 6: python open and read file with
with open('pagehead.section.htm','r') as f:
output = f.read()