Python Tutorial: File Objects - Reading and Writing to Files

Corey Schafer · 2.1M views · 2016 · 24:33

Open on YouTube

Python, Ruby & scripting languagesEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about reading, writing or chunking files in Python, and as a basics refresher for beginners.

Recommended by 4 people across 4 different months, 2019 to 2023.

What it is

A roughly 24-minute Python tutorial by Corey Schafer on working with file objects. It covers reading and writing text files, opening several files at once, and copying binary files such as images, with code available on GitHub.

What people said

Recommends Popescu David Ioan · 2019-08 · Stack Overflow · on “How to print more variables into file?”

You can have the values into a list, like: items = [1,8,9,9,6,6] with open('test.txt, 'r') as f: for elem in items[:-1]: -- for each element instead of last print(elem, end="-") -- print the value and the separator if (len(items) > 1): print(items[-1]) -- print last item without separator A very well-made tutorial about reading/writing to files in python can be watched here: [this video]

Recommends Alexander Riedel · 2020-11 · Stack Overflow · on “how to add a text dynamically to several files in python”

please check out some python bascis. really just check youtube [this video] or something. I would create a function of the solution i provided to you and call it for every file you want to change. Instead of inserting (`insert()`) you can of course directly set the list elements to the desired values

Recommends Jay Lynch · 2020-12 · Stack Overflow · on “Read list of large .asc type files in python .memory related issue”

You would feed the data into chunks with a for loop. Cory Schafer's video demonstrates this in his video: [this video]

Recommends guy007 · 2023-03 · Stack Overflow · on “How to go from pandas.ExcelWriter to models.FileField”

You do not need pandas.ExcelWriter to write an inmemory Excel file. You write it directly to io.BytesIO(). This four-minutes video pointed me to the solution: Python Tutorial: File Objects - Reading and Writing to Files - Corey Schafer [this video] . Do not forget to close the files after you're done. Here is the modified code: def planSaveFile(request, pk): plan = get_object_or_404(Plan, pk=pk) file_name = "foo.xlsx" # creation of an Excel file saved in memory df = pd.DataFrame({"A": [1, 2, -3], "B": [1, 2, 6]}) file_stream = io.BytesIO() df.to_excel(file_stream, sheet_name="sheet1") file_stream.seek(0) file = File(file_stream) # creating an instance of DocuPlan doc = DocuPlan( plan=plan, user=r