This commit is contained in:
Yavuz Sava 2024-11-03 11:04:13 +03:00
parent 203f3cbd92
commit 6f01dfbb7f

View File

@ -205,12 +205,168 @@
" writer.writerows(users)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Study guide: .csv files\n",
"The most common format for importing and exporting data for spreadsheets is a .csv format. A Comma Separated Values (.csv) file is a plain text file that uses—you guessed it—commas to separate each piece of data. You may already be familiar with .csv files if you have saved a spreadsheet in the .csv format. Here is a simple example of a .csv file displaying employee information:\n",
"\n",
"Name, Department, Salary\n",
"\n",
"Aisha Khan, Engineering, 80000\n",
"\n",
"Jules Lee, Marketing, 67000\n",
"\n",
"Queenie Corbit, Human Resources, 90000\n",
"\n",
"Notice that each row represents an employees information, and the values are separated by commas. \n",
"\n",
"In this reading, you will examine different commands to use when working with .csv files in Python and be provided with additional links for more information.\n",
"\n",
"Module contents\n",
"The .csv module is a built-in Python functionality used to read and work with .csv files. Lets look at how the .csv module defines some of these functions:\n",
"\n",
"csv.reader This function returns a reader object that iterates over lines in the .csv file.\n",
"\n",
"csv.writer This function returns a writer object thats responsible for converting the users data into delimited strings on the given file-like object.\n",
"\n",
"class csv.DictReader This function creates an object that functions as a regular reader but maps the information in each row to a dictionary whose keys are given by the optional fieldname parameters.\n",
"\n",
"Dialects and formatting parameters\n",
"Dialects are rules that define how a .csv file is structured, and parameters are formed to control the behavior of the .csv reader and writer and live within dialects. The following features are supported by dialects:\n",
"\n",
"Dialect.delimiter This attribute is a one-character string used to separate fields and defaults to a comma.\n",
"\n",
"Dialect.quotechar This attribute is a one-character string used to quote fields containing special characters and defaults to .\n",
"\n",
"Dialect.strict This attributes default is False, but when True, exception csv.Error will be raised if an error is detected.\n",
"\n",
"Reader objects\n",
"A reader object contains the following public methods and attributes:\n",
"\n",
"csvreader._next_() This method returns the next row of the readers iterable object as a list or a dictionary, parsed properly to the current dialect. Typically, you would call this next(reader).\n",
"\n",
"csvreader.dialect This attribute is a read-only description of the dialect in use by the parser.\n",
"\n",
"Writer objects\n",
"Writer objects provide you the capability to write data to a .csv file. Lets look at a couple of public methods and attributes for writer objects:\n",
"\n",
"csvwriter.writerows(rows) This method writes all elements in rows to the writers file object and formats following the current dialect.\n",
"\n",
"csvwriter.dialect This attribute is a read-only description of the dialect being used by the writer.\n",
"\n",
"Key takeaways\n",
"If you havent worked with .csv files yet, its only a matter of time. Become familiar with the .csv modules reader and writer objects to work more efficiently with .csv files. The modules, features, and attributes in this reading are only some of the commands that can be used while working with .csv files. \n",
"\n",
"Resources for more information\n",
"This \n",
"document https://docs.python.org/3/library/csv.html\n",
" provides additional information on how to read and write functions using .csv files.\n",
"\n",
"This \n",
"document https://realpython.com/python-csv/\n",
" provides additional information on what a .csv file is, how to parse .csv files with Pythons built-in .csv library, and how to parse .csv files with the pandas library."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1\n",
"We're working with a list of flowers and some information about each one. The create_file function writes this information to a CSV file. The contents_of_file function reads this file into records and returns the information in a nicely formatted block. Fill in the gaps of the contents_of_file function to turn the data in the CSV file into a dictionary using DictReader."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
"source": [
"import os\n",
"import csv\n",
"\n",
"# Create a file with data in it\n",
"def create_file(filename):\n",
" with open(filename, \"w\") as file:\n",
" file.write(\"name,color,type\\n\")\n",
" file.write(\"carnation,pink,annual\\n\")\n",
" file.write(\"daffodil,yellow,perennial\\n\")\n",
" file.write(\"iris,blue,perennial\\n\")\n",
" file.write(\"poinsettia,red,perennial\\n\")\n",
" file.write(\"sunflower,yellow,annual\\n\")\n",
"\n",
"\n",
"# Read the file contents and format the information about each row\n",
"def contents_of_file(filename):\n",
" return_string = \"\"\n",
"\n",
" # Call the function to create the file \n",
" create_file(filename)\n",
"\n",
" # Open the file\n",
" with open(filename, 'r') as open_file:\n",
" # Read the rows of the file into a dictionary\n",
" rows = csv.DictReader(open_file)\n",
" # Process each item of the dictionary\n",
" for row in rows:\n",
" return_string += \"a {} {} is {}\\n\".format(row[\"color\"], row[\"name\"], row[\"type\"])\n",
" return return_string\n",
"\n",
"\n",
"#Call the function\n",
"print(contents_of_file(\"flowers.csv\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import csv\n",
"\n",
"# Create a file with data in it\n",
"def create_file(filename):\n",
" with open(filename, \"w\") as file:\n",
" file.write(\"name,color,type\\n\")\n",
" file.write(\"carnation,pink,annual\\n\")\n",
" file.write(\"daffodil,yellow,perennial\\n\")\n",
" file.write(\"iris,blue,perennial\\n\")\n",
" file.write(\"poinsettia,red,perennial\\n\")\n",
" file.write(\"sunflower,yellow,annual\\n\")\n",
"\n",
"# Read the file contents and format the information about each row\n",
"def contents_of_file(filename):\n",
" return_string = \"\"\n",
"\n",
" # Call the function to create the file \n",
" create_file(filename)\n",
"\n",
" # Open the file\n",
" with open(filename, 'r') as open_file:\n",
" # Read the rows of the file\n",
" rows = csv.reader(open_file)\n",
" next(rows, None)\n",
" # Process each row\n",
" for row in rows:\n",
" name, color, type = row\n",
" # Format the return string for data rows only\n",
"\n",
" return_string += \"a {} {} is {}\\n\".format(name,color,type)\n",
" return return_string\n",
"\n",
"#Call the function\n",
"print(contents_of_file(\"flowers.csv\"))"
]
}
],
"metadata": {