Рубрики
Без рубрики

Обучение Python – 6 неделя 6

Это была моя последняя неделя Питона! Чтобы закончить это, я узнал о файле IO и модуль ОС, который … помечен Python, обучение.

Это была моя последняя неделя Питона! Чтобы завершить его, я узнал о файле IO и модуль ОС, который поможет с созданием файлов и запущенных файлов.

Файл IO.

Вы можете использовать Python для открытия файлов, и есть несколько способов сделать это, используя файл IO. Вы можете использовать это, чтобы прочитать из файла, добавить в существующий файл или перезаписать файл. Один просто использует метод открытия, который необходимо выполнить методом закрытия, а второе использование, используя все это для вас: первый вариант:

myfile = open('/Users//Documents/Coding/Python/LearningPython/fileIO-example/sample.txt') # cant have this file be opened more than once

content = myfile.read() # reads the contents of sample.txt from beginning to end
print(content)

myfile.seek(0) # will put the cursor at the beginning of the file. resets the cursor

print("---------------")
data = myfile.read() # will not read if printed. The read function takes the cursor from the beginning all the way to the end. so when the content variable is printed the cursor is at the end and will not go back.
print(data)

myfile.seek(0) # will put the cursor at the beginning of the file. resets the cursor

print("---------------")

content_list = myfile.readlines() # to read each line there is a readlines method. each line in the file will be saved in its own element in the list

myfile.close() # will close the file

Второй вариант: (я предпочитаю таким образом)

with open('/Users/evanpavone/Documents/Coding/Python/LearningPython/fileIO-example/sample.txt', mode='a') as my_file:
    """
    This open syntax already opens and closes the file
    If I change the filename it will make a new file in that location if I use the write mode
    MODES:
    a = append - adds to the file
    w = write - overwrites the file. The data will be replaced
    r = read - cannot write to it. Read only mode
    r+ = read and write
    w+ = override the file completely and have the ability to read it
    """
    my_file.write("\nThis is my sentence") # appended to the end of the file

Файл IO Обработка исключений

На прошлой неделе я говорил о обработке исключений, используя попытку, кроме. Ну, на этой неделе я узнал, что вы можете указать, что делать для каждого типа ошибки. Например, если бы у меня был типError, я мог бы указать, что произойдет, если произошла ошибка типа, если я столкнулся с моим кодом.

my_file = None

try:
    my_file = open('/Users/evanpavone/Documents/Coding/Python/LearningPython/fileIO-example/sample.txt', mode="r")
    print(my_file.read())
except IOError:
    """
    There are different types of exception errors. TypeError, FileNotFoundError etc...
    You can capture specific errors
    """
    print("Issue with working with the file...")
except:
    # general catch all error
    print("Error occurred, logging to the system")
finally:
    if my_file != None:
        my_file.close()
    print("This will always run regardless of whether we have an exception or not")

print("This line was run...")

ОС Модуль

Из того, что я узнал о модуле ОС, состоит в том, что он помогает с файлами и убедиться, что папка содержит файлы и т. Д. ОС модуль все начинается с импорта ОС в верхней части файла импорт Операционные системы . Импорт ОС позволяет использовать кучу способов, таких как getcwd, mkdir, makedirs, rmdir и т. Д. Вот куча методов в модуле ОС:

os.cwd() # gets the current working directory
os.chdir("/Users//Desktop") # changes directory location - in this case changes directory to desktop
os.listdir() # lists the contents of the directory
os.mkdir() # creates a folder in the current directory
os.makedirs() # creates multiple directories - good for having nested folders
os.rmdir() # deletes specific directory
os.remove() # removes files from the directory
os.walk() # "walks you through a directory and tells you each file and folder - I will show example with a for loop
os.environ.get("HOME") + "/" + "myfile.txt" # ->  /Users//myfile.txt
os.path.join(os.environ.get("HOME"), "myfile.txt" # -> /Users//myfile.txt
os.path.basename("/bin/tools/myfile.txt") # myfile.txt - used to get basename... thats the file at the directory location given
os.path.dirname("/bin/tools/myfile.txt") #  /bin/tools - get the directory name only, not the file
os.path.split("/bin/tools/myfile.txt") # ('/bin/tools', 'myfile.txt') - will give directory name and basename in a tuple
os.path.exists("/bin/tools/myfile.txt") # False - used to check if the path exists on the computer
os.path.isfile("/bin/tools/myfile.txt") # used to check if file exists in the specified path
os.path.isdir("/bin/tools/myfile.txt") # check if directory exists in the specified path
os.path.splitext("/bin/tools/myfile.txt") # ('/bin/tools/myfile', '.txt') - get file with path and file extension in a tuple

Пример использования метода прогулки в контуре для цикла:

import os

for dirpath, dirnames, filenames in os.walk("/Users//Documents/Coding/Python/LearningPython/myfolder"):
    # unpacking
    print(dirpath)
    print(dirnames)
    print(filenames)
    print(" ------------ ")

"""
/Users//Documents/Coding/Python/LearningPython/myfolder - dirpath
['stuff'] - dirnames
['sample.txt'] - filenames
 ------------ 
/Users//Documents/Coding/Python/LearningPython/myfolder/stuff - dirpath
['data'] - dirnames
['sample.txt'] - filenames
 ------------ 
/Users//Documents/Coding/Python/LearningPython/myfolder/stuff/data - dirpath
[] - dirnames - means no directory
['peacock.jpeg'] - filenames
 ------------ 
"""

Что я думаю

Я уже начинаю думать о возможностях, используя их. Мне любопытно посмотреть, смогу ли я сделать сценарий, который установит выбранный язык на ПК. Вроде, если бы я хотел установить Rails на компьютер, я мог бы запустить файл, который спросит меня, какой язык я хочу установить, и я бы выбрал Rails, и он пройдет через процесс установки его. Я просто бродягаюсь прямо сейчас Но мне очень любопытно.

Что теперь

Поскольку это была моя последняя неделя обучения Python, я собираюсь получить лучшее понимание и, надеюсь, сдам сертификационный экзамен в ближайшие несколько недель. Мне было очень весело с Python, и я думаю, что это там с моими любимыми языками.

Оригинал: “https://dev.to/evanrpavone/learning-python-week-6-3mb0”