Python read csv to string

Python read CSV to string conversion

[(‘ID’, ‘Value’), (1, ‘a’), (2, ‘b’), (3, ‘c’)] isn’t a string. It’s a list of tuples. The first tuple contains 2 strings, the other tuples contain an int and a string. So do you want that list, or do you really want a string representation of that list?

I just want to read the csv that contains two columns like in the question and then need to convert to above mentioned format(even its a string or list or tuples). Am not good in Python. So saying the above representation as string

2 Answers 2

To produce the list [(‘ID’, ‘Value’), (1, ‘a’), (2, ‘b’), (3, ‘c’)] from that CSV data you need to convert the number strings to integer. Here’s one way to do that in Python 2.

import csv data = [] with open('sample.csv', 'rb') as csvfile: reader = csv.reader(csvfile, skipinitialspace=True) data.append(tuple(next(reader))) for num, val in reader: data.append((int(num), val)) print data 

The csv.reader yields each row of the CSV data as a list. We need to extract the items from that list and convert the 1st one to an int . And then we can pack the two items into a tuple and append it to the data list. However, the header line contains two strings, so we don’t want to perform that conversion on the header line.

data.append(tuple(next(reader))) 

gets the header line and just converts it to a tuple and appends the result to our data list.

Note that the Python 2 csv module requires you to open the file in ‘rb’ mode, but in Python 3 you need to open the file in ‘r’ mode. Please see the respective module docs for further details. Apart from that, and using the print function instead of the print statement, no other changes are needed to run the above code on Python 3.

Источник

Convert CSV import to a string

Instead of printing the rows, I would like the rows to equal data. Then I can just say print(data) . New to python and writing scripts.

So you want data to be a string that is essentially your csv with delimiters replaced by single-spaces?

To help me know how specific and detailed to make the answer, the first script that you have there, do you understand how it works or did you just copy it from somewhere? If you understand the mechanics of that script, the answer will be a lot easier to explain, however if you don’t, a python tutorial will be more your speed.

Читайте также:  Javascript arguments function name

I used docs.python.org for the structure. Yes juanpa, i believe that is what i would like. Instead of «value» It should be a string. I will edit the name.

1 Answer 1

import csv with open('2017020397.csv', newline='') as f: data = '\n'.join(' '.join(row) for row in csv.reader(f)) print(data) 
LastName StartTime EndTime Duration Period TeamAbbrev Pos Bouwmeester 0:00 0:37 0:37 1 STL D Schwartz 0:00 0:40 0:40 1 STL W Foligno 0:00 0:40 0:40 1 MIN W Pietrangelo 0:00 0:48 0:48 1 STL D Suter 0:00 0:40 0:40 1 MIN D 

In order to leave the header out, you’d need to do it slightly differently:

with open('2017020397.csv', newline='') as f: reader = csv.reader(f) next(reader) # Skip header row. data = '\n'.join(' '.join(row) for row in reader) print(data) 
Bouwmeester 0:00 0:37 0:37 1 STL D Schwartz 0:00 0:40 0:40 1 STL W Foligno 0:00 0:40 0:40 1 MIN W Pietrangelo 0:00 0:48 0:48 1 STL D Suter 0:00 0:40 0:40 1 MIN D 

Источник

Python Convert CSV to Text File (.csv to .txt)

Be on the Right Side of Change

💬 Challenge: How to convert a CSV file to a text file in Python?

Here’s the content of an example CSV file «my_file.csv» used in our code snippet below:

Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000

If you visualize this CSV in table form, it looks like this:

Name Job Age Income
Alice Programmer 23 110000
Bob Executive 34 90000
Carl Sales 45 50000

The basic problem is to convert the CSV file «my_file.csv» to a new TXT file «my_file.txt» as is without changing its content

Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000

We start with exploring this basic challenge and build from there by changing the delimiter and using Pandas to access individual columns.

But first things first: How to convert a CSV file to a TXT file without changing its contents?

Method 1: CSV to TXT Unchanged

If you want to keep the content (including the delimiter ‘,’ ) in the CSV file unmodified, the conversion is simple: read the .csv file and write its content into a new .txt file using the open() , read() , and write() functions without importing any library.

In other words, perform the three steps to write a CSV to a TXT file unmodified:

  1. Open the CSV file in reading mode and the TXT file in writing mode.
  2. Read the CSV file and store it in a variable.
  3. Write the content into the TXT file.

Here’s the code snippet that solves our basic challenge:

# 1. Open the CSV file in reading mode and the TXT file in writing mode with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: # 2. Read the CSV file and store in variable content = f_in.read() # 3. Write the content into the TXT file f_out.write(content)

😲 Little-Known Fact: Python allows multiple expressions in the context manager ( with opening line) if you separate them with a comma.

The content of the .csv and .txt files is identical:

Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000

So far, so good. But what if you have a slightly different problem:

Читайте также:  Для удобства создания веб-страниц рекомендуется использовать HTML-редактор

Method 2: CSV to TXT Empty Space Delimiter

Challenge: How to convert a CSV file to a TXT file in Python by replacing the delimiter ‘,’ with the empty space ‘ ‘ ?

Example: Convert the following file ‘my_file.csv’ …

Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000
Name Job Age Income Alice Programmer 23 110000 Bob Executive 34 90000 Carl Sales 45 50000

Here’s the simple solution to this challenge:

If you want to change the delimiter ‘,’ to an empty string ‘ ‘ in the new TXT file, read the .csv file and write its content into a new .txt file using the open() , read() , string.replace() , and write() functions without importing any library.

To convert a CSV to a TXT file in Python, perform the following steps:

  1. Open the CSV file in reading mode and the TXT file in writing mode.
  2. Read the CSV file into a string.
  3. Create a new string by replacing all occurrences of the delimiter ‘,’ with the empty string ‘ ‘ .
  4. Write the content into the TXT file.
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: content = f_in.read().replace(',', ' ') f_out.write(content)

So far, so good. But in Python, there are always many ways to solve a problem. Let’s have a look at a powerful alternative to the no-library approach used before:

Method 3: CSV to TXT using Pandas

Assuming you’ve already installed pandas in your local environment, you can write a CSV to a TXT file in Python pandas using the following four steps:

  1. Import the pandas library.
  2. Read the CSV file into a DataFrame using pd.read_csv() .
  3. Convert the DataFrame to a String using the built-in str() function.
  4. Print the string to a file using the file argument of the print() function, for example.

Here’s the basic Python example:

import pandas as pd df = pd.read_csv('my_file.csv') content = str(df) print(content, file=open('my_file.txt', 'w'))

😲 Little-Known Fact: Python’s print() function allows you to write a string directly into a file object if you use the file argument as shown in the code snippet.

The output of the previous code snippet is as follows:

Name Job Age Income 0 Alice Programmer 23 110000 1 Bob Executive 34 90000 2 Carl Sales 45 50000

Let’s have a look at the last variation of the “CSV to TXT” problem addressed in this tutorial:

Method 4: CSV Columns or Rows to TXT using Pandas

How to write one or more individual columns or rows of the CSV file into a TXT file using Python Pandas?

  1. Import the pandas library.
  2. Read the CSV file into a DataFrame using pd.read_csv() .
  3. Select the column(s) or row(s) to write into the TXT file from the DataFrame using Pandas indexing or slicing.
  4. Call df.to_string() to convert the DataFrame to a string in a human-readable way.
  5. Print the string to a file using the file argument of the print() function, for example.
import pandas as pd df = pd.read_csv('my_file.csv') content = str(df['Name']) print(content, file=open('my_file.txt', 'w'))

The content in a new file ‘my_file.txt’ :

Читайте также:  Php подключить все папки

Of course, you can also select individual rows or multiple columns like so:

import pandas as pd df = pd.read_csv('my_file.csv') content = df['Name'][:2].to_string() print(content, file=open('my_file.txt', 'w'))

The content of the new file ‘my_file.txt’ shows that only the first two rows have been taken due to the slicing operation [:2] in the previous code snippet:

Done! You’ve earned some programming enjoyment:

Programmer Humor

Question: How did the programmer die in the shower? ☠️

Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.

More Python CSV Conversions

🐍 Learn More: I have compiled an “ultimate guide” on the Finxter blog that shows you the best method, respectively, to convert a CSV file to JSON, Excel, dictionary, Parquet, list, list of lists, list of tuples, text file, DataFrame, XML, NumPy array, and list of dictionaries.

Text to CSV: If you want to learn how to convert a text file back to a CSV, feel free to check out this guide on the Finxter blog.

Conclusion

I hope you enjoyed reading this article and learned something new. Feel free to join our email newsletter with free cheat sheets and weekly Python tutorials:

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Оцените статью