Featured
- Get link
- X
- Other Apps
File programs
In this post lets see some example how to read , write ,rename and delete the file using python file Operators.
To read a file:
print(f1.read())
f1.close()
To read a file using with statement:
print(file.read())
To write into a file:
In write operation you can write anything into a file using write() and writelines(). If the file is not not present the write mode create a new file with a given name. Every time you write something it overwrite the old content. It takes all data as strings.
print(f1.write("hello"))
L =["hi\n","hello\n","welcome\n"]
print(f1.writelines(L))
f1.close
(Go to the file and see the words you entered)
To write using with statement:
print(file.write("hello")
To append the text:
Append is nothing but adding data at the last. It is same as write mode we only change the access mode
print(f1.write("have a good day"))
Other Operators:
Other than read, write and append we can also perform some Operator but to use that we should import some module. We have seen what is module and how does it work in the before post. So lets import the module os stands for operating system to perform some Operations.
os.rename("use.txt","newfile")
To remove file:
We can use remove function to remove a file.
os.remove("use.txt")
Directory function:
Using os module we can create, delete and navigate through it
mkdir("newfolder)"
chdir("..")
rmdir("newfolder")
We can use mkdir() to make directory, chdir() to change directory and rmdir() to remove directory
By using("..") we navigate back one directory. If we want to specify a whole path like c:\user\desktop then we should use double backslash because python use single backslash for other purposes.
Example:
Copying content of one file to new file:
with open("use.txt","w") as file:
file.write(f1.read())
The content of file newfile txt will be copied to new file use.txt
Python file operation are simple. try programming every day to gain more knowledge and fun experience.
Try these program with files which you created. add some lines into it read it rename and remove it. Hope you understand this if not comment and share your thoughts!!!!
- Get link
- X
- Other Apps
Comments
Post a Comment