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# Note, if you're getting unwanted newline characters with this approach,
22# you can run: file_data = filename.read().splitlines() instead
23
24# Basic syntax for a delimited file with multiple fields:
25import csv
26with open('/path/to/filename.extension', 'open_mode') as filename:
27 file_data = csv.reader(filename, delimiter='delimiter')
28 data_as_list = list(file_data)
29# Where:
30# - csv.reader can be used for files that use any delimiter, not just
31# commas, e.g.: '\t', '|', ';', etc. (It's a bit of a misnomer)
32# - csv.reader() returns a csv.reader object which can be iterated
33# over, directly converted to a list, and etc.
34
35# Importing data using Numpy:
36import numpy as np
37data = np.loadtxt('/path/to/filename.extension',
38 delimiter=',', # String used to separate values
39 skiprows=2, # Number of rows to skip
40 usecols=[0,2], # Specify which columns to read
41 dtype=str) # The type of the resulting array
42
43# Importing data using Pandas:
44import pandas as pd
45data = pd.read_csv('/path/to/filename.extension',
46 nrows=5, # Number of rows of file to read
47 header=None, # Row number to use as column names
48 sep='\t', # Delimiter to use
49 comment='#', # Character to split comments
50 na_values=[""]) # String to recognize as NA/NaN
51
52# Note, pandas can also import excel files with pd.read_excel()
1import pandas as pd
2
3df = pd.read_excel (r'C:\Users\Ron\Desktop\Product List.xlsx') #place "r" before the path string to address special character, such as '\'. Don't forget to put the file name at the end of the path + '.xlsx'
4print (df)
5
1you should be in the same dir as .py file
2
3df = pd.read_csv('your_file_name.csv')