1# Basic syntax:
2with open('/path/to/filename.extension', 'open_mode') as filename:
3 file_data = filename.readlines() # Or filename.read()
4# Where:
5# - open imports the file as a file object which then needs to be read
6# with one of the read options
7# - readlines() imports each line of the file as an element in a list
8# - read() imports the file contents as one long new-line-separated
9# string
10# - open_mode can be one of:
11# - "r" = Read which opens a file for reading (error if the file
12# doesn't exist)
13# - "a" = Append which opens a file for appending (creates the
14# file if it doesn't exist)
15# - "w" = Write which opens a file for writing (creates the file
16# if it doesn't exist)
17# - "x" = Create which creates the specified file (returns an error
18# if the file exists)
19# Note, "with open() as" is recommended because the file is closed
20# automatically so you don't have to remember to use file.close()
21
22# Basic syntax for a delimited file with multiple fields:
23import csv
24with open('/path/to/filename.extension', 'open_mode') as filename:
25 file_data = csv.reader(filename, delimiter='delimiter')
26 data_as_list = list(file_data)
27# Where:
28# - csv.reader can be used for files that use any delimiter, not just
29# commas, e.g.: '\t', '|', ';', etc. (It's a bit of a misnomer)
30# - csv.reader() returns a csv.reader object which can be iterated
31# over, directly converted to a list, and etc.
32
33# Importing data using Numpy:
34import numpy as np
35data = np.loadtxt('/path/to/filename.extension',
36 delimiter=',', # String used to separate values
37 skiprows=2, # Number of rows to skip
38 usecols=[0,2], # Specify which columns to read
39 dtype=str) # The type of the resulting array
40
41# Importing data using Pandas:
42import pandas as pd
43data = pd.read_csv('/path/to/filename.extension',
44 nrows=5, # Number of rows of file to read
45 header=None, # Row number to use as column names
46 sep='\t', # Delimiter to use
47 comment='#', # Character to split comments
48 na_values=[""]) # String to recognize as NA/NaN
49
50# Note, pandas can also import excel files with pd.read_excel()
1with open('filename', 'a') as f: # able to append data to file
2 f.write(var1) # Were var1 is some variable you have set previously
3 f.write('data')
4 f.close() # You can add this but it is not mandatory
5
6with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)
7
8with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail
9
10with open('filename', 't') as f: # opens the file in text mode (also is defualt)
11
12with open('filename', 'b') as f: # Use if your file will contain binary data
13
14with open('filename', 'w') as f: # Open file with ability to write, will also create the file if it does not exist (if it exists will cause it to fail)
15
16with open('filename', '+') as f: # Opens file with reading and writing
17
18# You can combine these as you like with the + for reading and writing
1document = 'document.txt'
2file = open(document, 'r')
3# 'r' to read. it can be replaced with:
4# 'w' to write (overwrite)
5# 'a' to append (add to the end)
6# 'w+' makes a new file if one does not already exist of that name
7# 'a+' same as 'w+' but appends if the file does exist
8# 'x' creates file for writing, but fails if file already exists
9
10##go to beginning of document. not required but good for consistency.
11file.seek(0)
12
13##print all lines in document, except empty lines:
14for line in file:
15 k = line.strip()
16 print k
17
18##close the file after you are done
19file.close()
20
21
22##this also works to open a file, and is more error proof:
23with open(document) as filestream:
24 for i in filestream:
25 k = i.strip()
26 print k
1# Reference https://docs.python.org/3/library/functions.html#open
2
3# Method 1
4file = open("welcome.txt", "r") # mode can be r(read) w(write) and others
5data = file.read()
6file.close()
7
8# Method 2 - automatic close
9with open("welcome.txt") as infile:
10 data = file.read()
11
1def main():
2 f= open("guru99.txt","w+")
3 #f=open("guru99.txt","a+")
4 for i in range(10):
5 f.write("This is line %d\r\n" % (i+1))
6 f.close()
7 #Open the file back and read the contents
8 #f=open("guru99.txt", "r")
9 #if f.mode == 'r':
10 # contents =f.read()
11 # print (contents)
12 #or, readlines reads the individual line into a list
13 #fl =f.readlines()
14 #for x in fl:
15 #print(x)
16if __name__== "__main__":
17 main()