0% found this document useful (0 votes)
4 views

pyscript

The document provides an overview of file operations in Python, including reading, writing, and iterating through files. It details various file modes, encoding options, and methods for obtaining file information such as size and modification time. Additionally, it covers directory management and moving files using both low-level OS functions and the Pathlib library.

Uploaded by

ram14linga
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

pyscript

The document provides an overview of file operations in Python, including reading, writing, and iterating through files. It details various file modes, encoding options, and methods for obtaining file information such as size and modification time. Additionally, it covers directory management and moving files using both low-level OS functions and the Pathlib library.

Uploaded by

ram14linga
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

#Review: Reading files

file = open("spider.txt")
print(file.readline())
print(file.readline())
print(file.read())
file.close()

file = open("spider.txt")
print(file.readline())
print(file.readline())
print(file.read())
file.close()
with open("spider.txt") as file:
print(file.readline())

#Review: Iterating through files

with open("spider.txt") as file:


for line in file:
print(line.upper())

file = open("spider.txt")
lines = file.readlines()
file.close()
lines.sort()
print(lines)

#Review: Writing files

with open("novel.txt", "w") as file:


file.write("It was a dark and stormy night")

#Study guide: Reading and writing files

with open("sample_data/declaration.txt", "rt") as textfile:


for line in textfile:
print(line)

f = open("sample_data/declaration.txt", “w”)

Mode

The mode argument is optional, and it specifies the mode in which the file is
opened. If omitted, it defaults to ”r” and that means opening for reading in text
mode. The common modes include:

“r” open for reading (default)

“w” open for writing, truncating the file first

“x” open for exclusive creation, failing if the file already exists

“a” open for writing, appending to the end of the file if it exists

“+” open for both reading and writing

Attempting to write to a file opened for read (“r”) will cause a runtime error.
Encoding

Python distinguishes between binary mode (“b”) and text mode (“t”). By default,
files are opened in the text mode, which means you read and write strings from and
to the file, which are encoded in a specific encoding. If encoding is not
specified, the default is platform-dependent. This means that locale.getencoding()
is called to get the current locale encoding. If you need to open the text in a
specific encoding, you must specify it.
1
f = open('workfile', 'w', encoding="utf-8")

#Review: More file information

os.path.getsize("spider.txt")
#This code will provide the file size

os.path.getmtime("spider.txt")
#This code will provide a unix timestamp for the file

import datetime
timestamp = os.path.getmtime("spider.txt")
datetime.datetime.fromtimestamp(timestamp)
#This code will provide the date and time for the file in an
#easy-to-understand format

os.path.abspath("spider.txt")
#This code takes the file name and turns it into an absolute path

# othere important mmethods in file operations

import os
file= "file.dat"
if os.path.isfile(file):
print(os.path.isfile(file))
print(os.path.getsize(file))
else:
print(os.path.isfile(file))
print("File not found")

---------------------------------

print(os.getcwd())
#This code snippet returns the current working directory.

os.mkdir("new_dir")
#The os.mkdir("new_dir") function creates a new directory called new_dir

os.chdir("new_dir")
os.getcwd()
#This code snippet changes the current working directory to new_dir.
#The second line prints the current working directory.

os.mkdir("newer_dir")
os.rmdir("newer_dir")
#This code snippet creates a new directory called newer_dir.
#The second line deletes the newer_dir directory.

import os
os.listdir("website")
#This code snippet returns a list of all the files and
#sub-directories in the website directory.

dir = "website"
for name in os.listdir(dir):
fullname = os.path.join(dir, name)
if os.path.isdir(fullname):
print("{} is a directory".format(fullname))
else:
print("{} is a file".format(fullname))

# Create a directory and move a file from one directory to another


# using low-level OS functions.

import os

# Check to see if a directory named "test1" exists under the current


# directory. If not, create it:
dest_dir = os.path.join(os.getcwd(), "test1")
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)

# Construct source and destination paths:


src_file = os.path.join(os.getcwd(), "sample_data", "README.md")
dest_file = os.path.join(os.getcwd(), "test1", "README.md")

# Move the file from its original location to the destination:


os.rename(src_file, dest_file)

# Create a directory and move a file from one directory to another


# using Pathlib.

from pathlib import Path

# Check to see if the "test1" subdirectory exists. If not, create it:


dest_dir = Path("./test1/")
if not dest_dir.exists():
dest_dir.mkdir()

# Construct source and destination paths:


src_file = Path("./sample_data/README.md")
dest_file = dest_dir / "README.md"

# Move the file from its original location to the destination:


src_file.rename(dest_file)

You might also like