jinawee
0
Q:

python file reading

file = open(“testfile.txt”,”w”) 
 
file.write(“Hello World”) 
file.write(“This is our new text file”) 
file.write(“and this is another line.”) 
file.write(“Why? Because we can.”) 
 
file.close() 
36
# Basic syntax:
with open('/path/to/filename.extension', 'open_mode') as filename:
  file_data = filename.readlines()	# Or filename.read() 
# Where:
#	- open imports the file as a file object which then needs to be read
#		with one of the read options
#	- readlines() imports each line of the file as an element in a list
#	- read() imports the file contents as one long new-line-separated 
#		string
#	- open_mode can be one of:
#		- "r" = Read which opens a file for reading (error if the file 
#			doesn't exist)
#		- "a" = Append which opens a file for appending (creates the 
#			file if it doesn't exist)
#		- "w" = Write which opens a file for writing (creates the file 
#			if it doesn't exist)
#		- "x" = Create which creates the specified file (returns an error
#			if the file exists)
# Note, "with open() as" is recommended because the file is closed 
#	automatically so you don't have to remember to use file.close()

# Basic syntax for a delimited file with multiple fields:
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)
# Where:
#	- csv.reader can be used for files that use any delimiter, not just
#		commas, e.g.: '\t', '|', ';', etc. (It's a bit of a misnomer)
#	- csv.reader() returns a csv.reader object which can be iterated 
#		over, directly converted to a list, and etc. 

# Importing data using Numpy:
import numpy as np
data = np.loadtxt('/path/to/filename.extension',
				delimiter=',', 	# String used to separate values
				skiprows=2, 	# Number of rows to skip
				usecols=[0,2], 	# Specify which columns to read
				dtype=str) 		# The type of the resulting array

# Importing data using Pandas:
import pandas as pd
data = pd.read_csv('/path/to/filename.extension',
				nrows=5, 		# Number of rows of file to read
				header=None, 	# Row number to use as column names 
	            sep='\t', 		# Delimiter to use 
	            comment='#', 	# Character to split comments
				na_values=[""])	# String to recognize as NA/NaN

# Note, pandas can also import excel files with pd.read_excel()
8
with open('filename', 'a') as f: # able to append data to file
	f.write(var1) # Were var1 is some variable you have set previously
	f.write('data') 
	f.close() # You can add this but it is not mandatory 

with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)

with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail

with open('filename', 't') as f: # opens the file in text mode (also is defualt)

with open('filename', 'b') as f: # Use if your file will contain binary data
  
with 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)
  
with open('filename', '+') as f: # Opens file with reading and writing

# You can combine these as you like with the + for reading and writing
7
with open("file.txt", "r") as txt_file:
  return txt_file.readlines()
2
with open(filename,"w") as f:
  f.write('Hello World')
15
# Reference https://docs.python.org/3/library/functions.html#open

# Method 1
file = open("welcome.txt", "r") # mode can be r(read) w(write) and others 
data = file.read()
file.close()

# Method 2 - automatic close
with open("welcome.txt") as infile:
  data = file.read()
4
fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
6
# "with" closes file for you after use, even if error encountered
# r - read, w - write, rb - read binary, wb - write binary

with open('dog_breeds.txt', 'r') as reader:
     # Read and print the entire file line by line
     for line in reader:
         print(line, end='')
8
with open('pagehead.section.htm','r') as f:
    output = f.read()
2
import pandas as pd
import os
print(pwd)#check default save path
file=pd.read_csv("C:\filePath") 
file.head()
2

New to Communities?

Join the community