Q:

file python

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(filename,"w") as f:
  f.write('Hello World')
15
#there are many modes you can open files in. r means read.
file = open('C:\Users\yourname\files\file.txt','r')
text = file.read()

#you can write a string to it, too!
file = open('C:\Users\yourname\files\file.txt','w')
file.write('This is a typical string')

#don't forget to close it afterwards!
file.close()
6
# 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

# File Io basics

'''
r - open file for reading (defualt mode)
w - open file for writing
x - creates file if it not exist
a - add more content to a file 
t - text mode (as a string )
b - binary mode 
+ - read and write (mostly used for updating file)
'''
3
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