\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{exotic} \pdfinfo{ /Title (files-python.pdf) /Creator (Cheatography) /Author (exotic) /Subject (Files Python Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{3494A3} \definecolor{LightBackground}{HTML}{F2F8F9} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Files Python Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{exotic} via \textcolor{DarkBackground}{\uline{cheatography.com/146713/cs/31784/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}exotic \\ \uline{cheatography.com/exotic} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 22nd April, 2022.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{x{3.44 cm} x{4.56 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{File Modes}} \tn % Row 0 \SetRowColor{LightBackground} \{\{width=14\}\}{\bf{Method/Keyword}} & {\bf{Meaning}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} {\bf{r}} & Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the {\bf{default mode}}. \tn % Row Count 8 (+ 6) % Row 2 \SetRowColor{LightBackground} {\bf{w}} & Opens a file for writing only, truncating the file first. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. \tn % Row Count 16 (+ 8) % Row 3 \SetRowColor{white} {\bf{x}} & Opens for exclusive creation, failing if the file already exists \tn % Row Count 19 (+ 3) % Row 4 \SetRowColor{LightBackground} {\bf{a}} & Opens a file for writing/appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. \tn % Row Count 29 (+ 10) % Row 5 \SetRowColor{white} {\bf{+}} & Open for updating (reading and writing) \tn % Row Count 31 (+ 2) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{3.44 cm} x{4.56 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{File Modes (cont)}} \tn % Row 6 \SetRowColor{LightBackground} {\bf{r+}} & Opens a file for both reading and writing. The file pointer placed at the beginning of the file. \tn % Row Count 5 (+ 5) % Row 7 \SetRowColor{white} {\bf{a+}} & Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing \tn % Row Count 15 (+ 10) % Row 8 \SetRowColor{LightBackground} {\bf{w+}} & Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. \tn % Row Count 23 (+ 8) % Row 9 \SetRowColor{white} {\bf{b}} & Binary mode \tn % Row Count 24 (+ 1) % Row 10 \SetRowColor{LightBackground} sdffds & kjhljhk \tn % Row Count 25 (+ 1) % Row 11 \SetRowColor{white} kjhjhk & hjkjkh \tn % Row Count 26 (+ 1) % Row 12 \SetRowColor{LightBackground} hjkjkh & hjkjh \tn % Row Count 27 (+ 1) % Row 13 \SetRowColor{white} hkjjkh & jhkjhkhjk \tn % Row Count 28 (+ 1) % Row 14 \SetRowColor{LightBackground} ghjkghj & hgjhjghjg \tn % Row Count 29 (+ 1) % Row 15 \SetRowColor{white} hjghjghjhjghgj & jhgghjghjhgj \tn % Row Count 30 (+ 1) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{3.44 cm} x{4.56 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{File Modes (cont)}} \tn % Row 16 \SetRowColor{LightBackground} ghghjhjg & jghghj \tn % Row Count 1 (+ 1) % Row 17 \SetRowColor{white} jghjhgjhg & hgjjhgghj \tn % Row Count 2 (+ 1) % Row 18 \SetRowColor{LightBackground} ghjghjghj & hgjghjghj \tn % Row Count 3 (+ 1) % Row 19 \SetRowColor{white} jhgghjghj & hjgjhgghjjh \tn % Row Count 4 (+ 1) % Row 20 \SetRowColor{LightBackground} ghjhgjghj & hgjhjg \tn % Row Count 5 (+ 1) % Row 21 \SetRowColor{white} jhggjhjhg & hgjjhgjhg \tn % Row Count 6 (+ 1) % Row 22 \SetRowColor{LightBackground} gjhjhghjg & hgjhjgjhgjhg \tn % Row Count 7 (+ 1) % Row 23 \SetRowColor{white} ghjghjgjh & ghjhjghjg \tn % Row Count 8 (+ 1) % Row 24 \SetRowColor{LightBackground} jghjhghgj & ghjhjgjghjgh \tn % Row Count 9 (+ 1) % Row 25 \SetRowColor{white} ghgjhgjh & ghjjhgjhg \tn % Row Count 10 (+ 1) % Row 26 \SetRowColor{LightBackground} ghjghgjhjg & hgjjghgjh \tn % Row Count 11 (+ 1) % Row 27 \SetRowColor{white} ghjjghgjh & hgjjghjghghj \tn % Row Count 12 (+ 1) % Row 28 \SetRowColor{LightBackground} hjghjgjghjhg & jjhggjhhjg \tn % Row Count 13 (+ 1) % Row 29 \SetRowColor{white} jhghjghjggjh & hjghgjjghjhg \tn % Row Count 14 (+ 1) % Row 30 \SetRowColor{LightBackground} gjhhjgjgh & hgjjhghjg \tn % Row Count 15 (+ 1) % Row 31 \SetRowColor{white} hjghgjgjhgjh & hjgjhgjhgghj \tn % Row Count 16 (+ 1) % Row 32 \SetRowColor{LightBackground} hgjhjgghjghj & jhghgjhjghgj \tn % Row Count 17 (+ 1) % Row 33 \SetRowColor{white} hjgjhgjhgjhg & hgjjhghjgjhg \tn % Row Count 18 (+ 1) % Row 34 \SetRowColor{LightBackground} jhgjhghjgjhghjg & ghjghjhgjgjhgjh \tn % Row Count 19 (+ 1) % Row 35 \SetRowColor{white} jhgghjhgjhjgjhg & hjghjghjghjgjhg \tn % Row Count 20 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.204 cm} x{2.432 cm} x{2.964 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{8.4cm}}{\bf\textcolor{white}{Functions}} \tn % Row 0 \SetRowColor{LightBackground} \{\{width=14\}\}{\bf{Method/Keyword}} & {\bf{Parameters}} & {\bf{Uses}} \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} {\bf{open()}} & filename and open mode (optional) & create a file object by \seqsplit{opening/creating} the file in the specified read/write mode \tn % Row Count 9 (+ 6) % Row 2 \SetRowColor{LightBackground} {\bf{with}} & - & use it together with open(); closes the file after the suite completes \tn % Row Count 14 (+ 5) % Row 3 \SetRowColor{white} {\bf{read()}} & size (optional) & read the file up to the size specified if set \tn % Row Count 17 (+ 3) % Row 4 \SetRowColor{LightBackground} {\bf{readline()}} & size (optional) & read a single line with a size limit if set \tn % Row Count 20 (+ 3) % Row 5 \SetRowColor{white} {\bf{readlines()}} & size (optional) & create a list of the read lines with an optional size hint \tn % Row Count 24 (+ 4) % Row 6 \SetRowColor{LightBackground} {\bf{write()}} & the string & write the string to the file that is opened with a certain writeable mode \tn % Row Count 29 (+ 5) % Row 7 \SetRowColor{white} {\bf{writelines()}} & the list of strings & write the list of strings to the file that is opened with a certain writeable mode \tn % Row Count 35 (+ 6) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{2.204 cm} x{2.432 cm} x{2.964 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{8.4cm}}{\bf\textcolor{white}{Functions (cont)}} \tn % Row 8 \SetRowColor{LightBackground} {\bf{seek()}} & offset, \seqsplit{whence=SEEK\_SET} & Change the stream position to the given byte offset \tn % Row Count 4 (+ 4) % Row 9 \SetRowColor{white} {\bf{truncate()}} & size=None & Resize the stream to the given size in bytes (or the current position if size is not specified). \tn % Row Count 11 (+ 7) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{File Modes}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Start}}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{r} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{w} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{a} \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{r+} \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{w+} \tn % Row Count 6 (+ 1) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{a+} \tn % Row Count 7 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{x} \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{readline()}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{with open('test.txt') as file: \newline file.readline() \newline file.readline(2) \# 2 characters from line 2 \newline file.readline(5) \# 3 characters from line 3 \newline file.readline() \newline file.readline() \newline \newline '0 Start Line 0 - Line 0 End 0\textbackslash{}n' \newline '1 ' \newline 'Start' \newline ' Line 1 - Line 1 End 1\textbackslash{}n' \newline ''} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{If you call the readline() method multiple times, the reading will be continued at where it was read last time. \newline {\bf{readline()}} method can also take in a size parameter, which will be used as a limit for reading the line. Again, reading is continued at where it was read last time.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Write a File}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{with open('test.txt', 'w') as file: \newline file.write('This is a writing method.') \newline \newline 25} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{The {\bf{w}} mode will truncate the file, and thus the file will only contain the new values. The {\bf{a}} mode will allow you to append new values to the existing file. \newline Printing the number of characters written can be suppressed by assigning the returned value to an underscore.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Reading Different Types of CSV}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{import csv \newline \newline with open('addresses.csv', newline='') as addresses\_csv: \newline address\_reader = \seqsplit{csv.DictReader(addresses\_csv}, delimiter=';') \newline \newline for row in address\_reader: \newline print(row{[}'Address'{]})} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{We change the delimiters to indicate where the different values start and stop. We pass {\bf{delimiter}} parameter, which is used to delineate separate fields in the CSV.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Writing a CSV File}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{big\_list = {[}\{'name': 'Fredrick Stein', 'userid': 6712359021, 'is\_admin': False\}{]} \newline \newline import csv \newline \newline with open('output.csv', 'w') as output\_csv: \newline fields = {[}'name', 'userid', 'is\_admin'{]} \newline output\_writer = \seqsplit{csv.DictWriter(output\_csv}, fieldnames=fields) \newline \newline \seqsplit{output\_writer.writeheader()} \newline \newline for item in big\_list: \newline \seqsplit{output\_writer.writerow(item)}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Open CSV in write mode, define {\bf{fields}}, instantiate CSV writer object and pass two arguments. \newline \newline {\bf{.writeheader()}} writes headers from fieldnames.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Read File}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{with open('test.txt') as file: \newline file.read(6) \# Size smaller than file size \newline \newline '0 Star'} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{When the size argument is omitted or set as negative, or set as an integer greater than the file size, all the file contents will be read. \newline \newline Reading a file for the second time will return an empty string.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{readlines()}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{with open('test.txt') as file: \newline file.readlines() \newline \# file.readlines(29) reads 29 characters, 30 reads whole of next line \newline \newline {[}'0 Start Line 0 - Line 0 End 0\textbackslash{}n', '1 Start Line 1 - Line 1 End 1\textbackslash{}n'{]}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{When size is set as a positive integer, it will read that many characters (or bytes in the binary mode) from the file and enough to complete that line.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{writelines()}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{with open('test.txt', 'w') as file: \newline file.writelines({[}'Line 0\textbackslash{}n', 'Line 1'{]}) \newline \newline \newline with open('test.txt') as file: \newline file.read() \newline \newline 'Line 0\textbackslash{}nLine 1'} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{This method will take in a list of strings as the parameter. How the lines are written (e.g., overwriting or appending) using this method is similar to the implementation of the write() method.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{What is a CSV File?}} \tn \SetRowColor{white} \mymulticolumn{1}{x{8.4cm}}{{\bf{Comma-Separated Values}} are usually the way that data from spreadsheet is exported into a portable format.% Row Count 3 (+ 3) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Reading a CSV File}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{import csv \newline \newline list\_of\_email\_addresses = {[}{]} \newline with open('users.csv', newline='') as users\_csv: \newline user\_reader = \seqsplit{csv.DictReader(users\_csv)} \newline for row in user\_reader: \newline \seqsplit{list\_of\_email\_addresses}.append(row{[}'Email'{]})} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{We can convert data into a dictionary using {\bf{*csv}} and its {\bf{DictReader}} object. \newline {\bf{newline=""'}} ensures that we don't mistake a line break in one of our data fields as a new row in CSV.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}