pyscript
pyscript
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())
file = open("spider.txt")
lines = file.readlines()
file.close()
lines.sort()
print(lines)
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:
“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
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")
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
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))
import os