To work with files in Python os and shutil are useful modules.The os module consists of methods related to files and directories.For working with Files in Python you need to use the File object which is a built in object in Python.It consists of some useful methods
- Open() Used to open a file
- Read () Used to read contents of the file
- Write () Used for writing to a file
- Append () Used for appending new content
To open a file called sample.txt having the full path as “C:\sample.txt”, you will use the following code.We are opening the file in read mode by specifying “r” as the second argument to the open method:
a=open(r'C:\sample.txt',"r")
Similarly to open the file in write mode you will use the following:
a=open(r'C:\sample.txt',"w")
Similarly for appending to an existing file you will pass “a” as the second argument.
You can use the following sample to read and print the contents of a file: a=open(r'I:\sample.txt',"r") b=a.readlines() print(b)
If you observe you can notice one important point above.We have used the character ‘r’ before string path argument in open method.This is required as “\” is a reseverd character in Python.If you want you can specify double slashed “\\” instead of character ‘r’ when specifying paths.
To list the contents of a directory you can use the os modules listdir method as:
print(os.listdir("I:\\"))
To move a file you can useĀ shutil module’s move method:
shutil.move("C:\\sample.txt", "K:\\sample.log")
similarly to copy a file from one location to another you can use the copy method:
shutil.copy("C:\\sample.txt", "K:\\sample.log")
Leave a Reply