FIFA-2022 Career Guide Free Tutorials Go to Your University Placement Preparation 
0 like 0 dislike
2.5k views
in Python Programming by Goeduhub's Expert (3.1k points)
edited by

In this article we will deal with how to open, read , write and close files in Python. Basically dealing with file handling in python. 

Related Links: Basic Python 

by (100 points)
Never used file handling till now, but now am excited to start with it.

5 Answers

0 like 0 dislike
by Goeduhub's Expert (3.1k points)
edited by
 
Best answer

Python File Handling

Reading and writing data to files using Python is pretty straightforward. To do this, you must first open files in the appropriate mode.File handling is an important part of any web application.

To start with file handling you  have to open file. To open file open() "open(filename, mode) "is used.

Mainly Three modes are used:

1."r",r opens the file in read only mode.

2."w",opens the file in  write mode,create a file if not exist.

3."a", opens the file for appending,create a file if not exist.

Python File Methods

FunctionExplanation
open()To open a file
close()Close an open file
fileno()Returns an integer number of the file
read(n)Reads ‘n’ characters from the file till end of the file
readable()Returns true if the file is readable
readline()Read and return one line from the file
readlines()Reads and returns all the lines from the file
seek(offset)Change the cursor position by bytes as specified by the offset
seekable()Returns true if the file supports random access
tell()Returns the current file location
writable()Returns true if the file is writable
write()Writes a string of data to the file
writelines()Writes a list of data to the file

Example (Reading Files)

f=open("text.txt",'r') 

print(f.read(5)) # read only five characters

f.close() # close an open file

f=open("text.txt",'r')

for i in f:

    print(i)

Output

GOedh 

GOedhub technologies providing training in data science.  

and also in ML and AI. 

Example (To write data to file )

f=open("text.txt",'w')

f.write ("GOedhub technologies providing training in data science")

f.close()

Note:- write mode first remove all existing data from file and then write data to the file.

Example (To append data to the file  )

f=open("text.txt",'a')

f.write ("Also in ML and AI")

Note:-append new data to the file without disturbing existing data.

Getting a directory listing

To get a list of all the files and folders in a particular directory in the filesystem, use os.listdir() in legacy versions of Python or os.scandir() in Python 3.x. os.scandir() is the preferred method to use if you also want to get file and directory properties such as file size and modification date.

os.listdir()- Returns a list of all files and folders in a directory

Example

import os 

l=os.listdir("C:\\Users\\apex\\Downloads") #path for directory 

for i in l:

    print(i)

Note:- display all the folders, and files in downloads  

os.scandir()- Returns an iterator of all the objects in a directory including file attribute information

Example

import os 

l=os.scandir("C:\\Users\\apex\\Desktop\\python")

for i in l:

    print(i)

Output 

<DirEntry 'Ex_81.py'> 

<DirEntry 'Ex_82.py'> 

<DirEntry 'Pandas.docx'> 

<DirEntry 'python'> 

 Note:- pathlib.Path.iterdir()- Returns an iterator of all the objects in a directory including file attribute information

List all files in a directory using scandir()

Example

basepath = 'Goeduhub _directory' 

 os.scandir(basepath) as entries:

 for i in entries:

 if i.is_file(): 

print(i.name)

Output

file1.py

 file3.txt

 file2.csv

Note:-All files display 

List all subdirectories using scandir()

Example

basepath = 'Goeduhub_directory' 

 os.scandir(basepath) as entries:

 for entry in entries: 

if entry.is_dir(): 

print(entry.name)

Output

sub_dir_c 

sub_dir_b

Note:- Display all the directories and sub-directories.

Making Directories

os.mkdir()-Creates a single subdirectory

os.makedirs()-Creates multiple directories, including intermediate directories

Example

import os 

os.mkdir("Goeduhub_directory")

Note:- It will create a sub directory with name "Goeduhub_directory" 


Python Tutorial 

Machine Learning Tutorial 

AI Tutorial

Free Online Tutorials

by (294 points)
I this module it's is used for web application
by (422 points)
File handling operations can be explained with example.
by (100 points)
in this article, i learned about file handling in python. how to create a new file and write in it. how to append some text. use of OS module. use of mkdir, scandir etc.
by (100 points)
basepath = 'Goeduhub _directory'

 os.scandir(basepath) as entries:

 for i in entries:

 if i.is_file():

print(i.name)


It is generating an error :

File "<ipython-input-33-902f2bdb4a9b>", line 3
    os.scandir(basepath) as entries:
                          ^
SyntaxError: invalid syntax
0 like 0 dislike
by (712 points)

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. 

  •  r “, for reading.
  •  w “, for writing.
  •  a “, for appending.
  •  r+ “, for both reading and writing
split(),with(),write(),append() are some functions uses in  it 
thank you 
0 like 0 dislike
by (232 points)
Topic-Python file handling

I learn how handle any file in python, how to write, read and write-read together in one time.
0 like 0 dislike
by (592 points)

1/05/2020

Python file handling operations also known as Python I/O deal with two types of files. They are:

  • Text files
  • Binary files

Even though the two file types may look the same on the surface, they encode data differently.

A text file is structured as a sequence of lines. And, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.

Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.

Syntax of the Python open function:

obj=open(file_name , access_mode, buffer)

Here,

  • The file_name refers to the file which we want to open.
  • The access_mode specifies the mode in which the file has to be opened. It can be ‘r’, which is used for opening a file only to read it in Python, or ‘w’ used for opening a file only to write into it. Similarly, ‘a’ opens a file in Python in order to append, and so on. For more access modes, refer to the table given below.
  • The buffer represents whether buffering is performed or not. If the buffer value is 0, then no buffering is performed, and when the buffer value is 1, then line buffering is performed while accessing the file.
0 like 0 dislike
by (391 points)
Date: 02/05/2020

Topic: File Handling in Python

here, i have learned how to start, open, read, write a file in python.

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.

Best Data Science Courses on Datacamp
Best Data Science Courses on Coursera
Best Data Science Courses on Udemy
Best Data Science Courses on Pluralsight
Best Data Science Courses & Microdegrees on Udacity
Best Artificial Intelligence[AI] Courses on Coursera
Best Machine Learning[ML] Courses on Coursera
Best Python Programming Courses on Coursera
Best Artificial Intelligence[AI] Courses on Udemy
Best Python Programming Courses on Udemy

Related questions

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy ||  Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 

 

Free Online Directory

...