AS
AS
X
Python
open()
"w" = write access
“+” to create the file if it doesn't already exist
“a” = append
“r” = read
write()
read()
Codice
f =
open
("newFile.txt",
"w+"
)
f.
write
("first line
\r
second line")
f.
close
Content of newFile.txt
first line
second line
Codice
f =
open
("newFile.txt",
"a"
)
f.
write
("
\r
appended line")
f.
close
Content of newFile.txt
first line
second line
appended line
Codice
f =
open
("newFile.txt",
"w"
)
f.
write
("Overwritten content
\r
second line")
f.
close
Content of newFile.txt
Overwritten content
second line
read()
Codice
f =
open
("newFile.txt",
"r"
)
c = f.
read
()
f.
close
print(c)
Output
Overwritten content
second line
readlines()
Codice
f =
open
("newFile.txt",
"r"
)
for
i
in
enumerate
(f.
readlines
())
:
print(
i
[0], "\t",
i
[1])
f.
close
Output
0
Overwritten content
1
second line
path.
exists()
path.
isfile()
path.
isdir()
Codice
import
os
from
os
import
path
print(
path.exists
("newFile.txt"))
print(path.
isfile
("newFile.txt"))
print(path.
isdir
("newFile.txt"))
Output
True
True
False
path.
realpath()
path.
split()
Codice
import
os
from
os
import
path
p
= path.
realpath
("newFile.txt")
print(
p
)
s
= path.
split
(
p
)
print(
s
[0])
print(
s
[1])
Output
C:\Users\pc\Desktop\prove\newFile.txt
C:\Users\pc\Desktop\prove
newFile.txt
path.
getmtime()
Return the last modification time of the file.
Codice
import
os
from
os
import
path
import
time
mt
= path.
getmtime
("newFile.txt")
print(
mt
)
t
= time.
ctime
(
mt
)
print(
t
)
Output
1713497639.5097
Fri Apr 04 05:33:59 2024
shutil.
copy()
shutil.
copystat()
(copy file metadata)
Codice
import
shutil
shutil.
copy
("newFile.txt", "newFile.txt.bkp")
shutil.
copy
("newFile.txt", "newFile.txt.bkpStat")
shutil.
copystat
("newFile.txt", "newFile.txt.bkpStat")
Example
os.
rename()
Codice
import
os
os.
rename
("newFile.txt.bkpStat", "newFile.txt.bkpStat_rev")
Example
indietro
Home
PHP
HTML e CSS
Javascript
C++
Python
SQL
Excel
Access
Power Apps
Power BI