Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit464e6bc

Browse files
committed
added handling files tutorial
1 parent43257d7 commit464e6bc

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#[How to Handle Files in Python using OS Module](https://www.thepythoncode.com/article/file-handling-in-python-using-os-module)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
importos
2+
3+
# print the current directory
4+
print("The current directory:",os.getcwd())
5+
6+
# make an empty directory (folder)
7+
os.mkdir("folder")
8+
# running mkdir again with the same name raises FileExistsError, run this instead:
9+
# if not os.path.isdir("folder"):
10+
# os.mkdir("folder")
11+
# changing the current directory to 'folder'
12+
os.chdir("folder")
13+
# printing the current directory now
14+
print("The current directory changing the directory to folder:",os.getcwd())
15+
16+
# go back a directory
17+
os.chdir("..")
18+
19+
# make several nested directories
20+
os.makedirs("nested1/nested2/nested3")
21+
22+
# create a new text file
23+
text_file=open("text.txt","w")
24+
# write to this file some text
25+
text_file.write("This is a text file")
26+
27+
# rename text.txt to renamed-text.txt
28+
os.rename("text.txt","renamed-text.txt")
29+
30+
# replace (move) this file to another directory
31+
os.replace("renamed-text.txt","folder/renamed-text.txt")
32+
33+
# print all files and folders in the current directory
34+
print("All folders & files:",os.listdir())
35+
36+
# print all files & folders recursively
37+
fordirpath,dirnames,filenamesinos.walk("."):
38+
# iterate over directories
39+
fordirnameindirnames:
40+
print("Directory:",os.path.join(dirpath,dirname))
41+
# iterate over files
42+
forfilenameinfilenames:
43+
print("File:",os.path.join(dirpath,filename))
44+
# delete that file
45+
os.remove("folder/renamed-text.txt")
46+
# remove the folder
47+
os.rmdir("folder")
48+
49+
# remove nested folders
50+
os.removedirs("nested1/nested2/nested3")
51+
52+
open("text.txt","w").write("This is a text file")
53+
54+
# print some stats about the file
55+
print(os.stat("text.txt"))
56+
57+
# get the file size for example
58+
print("File size:",os.stat("text.txt").st_size)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp