Tweets to CSV: Export Twitter (X) Posts to a Clean CSV File

- Flatten, then write. One row per post with fixed columns; join lists (hashtags, mentions, media) with
|so a cell never holds JSON. - Let the csv module quote. 85.8% of our 993 rows had a field that needed quotes; 75.2% of texts had a line break.
- IDs are text, always. Post IDs are 19 digits; Excel keeps 15, so all 993 post IDs in our sample changed when read as numbers.
- Open with
newline=""andencoding="utf-8-sig". Python's docs require the first for embedded newlines; the BOM is three bytes that tell Excel the file is UTF-8. - CSV is small. The 26-column CSV was 5.5% of the raw JSON size: 449 KB against 8.0 MB.
- Cost.
/twitter/user/last_tweetsreturns 20 posts a page at 15 credits per post ($0.15 per 1,000); this study's 993 posts cost about $0.15.
This page is about the CSV file itself: which columns to write for a post, how to flatten the nested JSON, and the quoting, encoding and ID-precision traps that turn a tweet export into a broken spreadsheet. It sits between three neighbors. Our Twitter JSON guide explains the raw response fields one by one; the Twitter dataset export guide plans a research corpus end to end (sampling, ethics, archiving); and the Twitter API to Excel guide covers Excel-specific routes such as Power Query. Here the job is narrower: produce one portable CSV that opens the same way in Excel, Google Sheets, pandas and R.
The advice below is measured rather than assumed. We exported 993 real posts from five organization accounts (@NASA, @github, @nvidia, @vercel, @Xbox) through /twitter/user/last_tweets, wrote them to a 26-column CSV with Python's csv module, and counted what happened: file size, column fill rates, rows that needed quoting, IDs that a spreadsheet would corrupt, and the time each step took. A 25-row sample of the result, organization-authored original posts only, is published at /blog/tweets-to-csv/sample.csv so you can open it in your own tools before you write any code.
The route works for any list of posts our API returns: a user's timeline, an advanced search such as from:NASA with a since_time: window, the replies under one post via a conversation_id: search, or a list of IDs. Only the fetch function changes; the schema, the writer and the import rules stay the same.
85.8%
Three ways to get tweets into a CSV
There are three practical routes, and they differ in how much of the file you control.
Your X archive. X's help center describes requesting an archive of your data from your account settings (help.x.com/en/managing-your-account/how-to-download-your-x-archive). Independent guides, including the EFF's, describe the posts arriving in a tweets.js file: JSON wrapped in a line of JavaScript, not a CSV, and only for the account you are logged into. It is a fine source for your own history, but you still have to flatten it, and every rule below still applies.
A no-code sheet. If you want a sheet that refreshes on a schedule rather than a file, our Google Sheets guide runs the same API from Apps Script and writes rows directly; Sheets then exports CSV through File > Download. The ID rule matters there too: write IDs with a leading apostrophe or into a column formatted as plain text.
A script. Writing the CSV yourself is the only route that controls the schema, the encoding and the quoting, and it is the route the rest of this page covers. The full script is in the code section below; it needs requests and an API key from the dashboard, and reads posts without any X account.
A 26-column schema for one row per post
A post in the API response is a nested object: the author is a sub-object, hashtags and links sit inside entities, media inside extendedEntities.media[], and reposts or quotes carry a whole second post inside retweeted_tweet or quoted_tweet. A CSV is flat, so the first decision is the column list. We used 26 columns in five groups; the table maps each column to the JSON field it comes from.
Join lists with a pipe, not a comma. A hashtag list written as AI,GPU is legal CSV once quoted, but every downstream tool then has to split a quoted comma list. A pipe (AI|GPU) never needs quoting and splits with one call in any language.
Store nested posts as an ID. A repost's retweeted_tweet is a complete post with its own author and metrics. Writing its text into your row mixes two authors in one record. Keep retweeted_tweet_id and, if you need the original, export it as its own row (fetch it with /twitter/tweets?tweet_ids=...).
Derive a type column. Filtering a CSV by type = original is far easier than checking three boolean columns. Our rule: repost if retweeted_tweet is present or the text starts with RT @; else reply if isReply; else quote if quoted_tweet is present; else original. In our sample that gave 626 originals, 333 reposts and 34 quotes (timelines leave replies out unless you pass includeReplies=true).
Which columns actually get filled
A schema is a promise; fill rates tell you what you get. Across 993 posts, 17 of the 26 columns were filled on every row. The rest depend on the kind of post, and two were empty by design.
Empty is not missing. Write an empty string for an absent value, not None, null or NaN; the csv module writes None as an empty field, but a hand-rolled str(value) writes the word None into your data. When you read the file back in pandas, an empty field becomes NaN, so count columns such as view_count need a nullable integer type (Int64) if you want them to stay integers.
view_count was always present in this sample (100.0%), but older posts from before X started counting views can return it empty, so treat it as optional in your schema.

Line breaks, commas, quotes and emoji: why naive CSV code breaks
RFC 4180, the closest thing CSV has to a standard, says fields containing line breaks, double quotes and commas should be enclosed in double quotes, and a double quote inside a quoted field is escaped by doubling it. Post text hits all three constantly.
Line breaks are the big one. Three in four posts in our sample had at least one; the median post with a break had 3, and one had 16. The 993 rows plus a header made a file of 3,589 physical lines. Anything that splits the file on line breaks (a for line in f loop, wc -l, a quick split("\n")) sees 2,595 rows that do not exist. Python's csv reader read all 993 rows back with every text field identical to what we wrote.
Do not strip the breaks to make the file "simpler". Replacing line breaks with spaces loses meaning in threads, lists and code snippets. Quote them instead; with QUOTE_MINIMAL, the csv module's default, only the fields that need it are quoted, which was 85.8% of our rows.
Unescape HTML entities on purpose. Post text arrives with &, < and > encoded as &, < and >. Python's html.unescape() converts named and numeric character references back to characters. Decide once whether your CSV holds display text (unescaped) or raw API text (escaped) and say so in a README next to the file.
t.co links are in the text. 64.0% of texts contained a shortened https://t.co/... link. The real destination is in entities.urls[].expanded_url, which is why the schema has an expanded_urls column.

Encoding: UTF-8, the BOM and Excel
Post text is Unicode. Our 993-row file held 2,164 non-ASCII characters (emoji, curly quotes, accented letters, a Japanese-language post), and 334 texts contained a character outside the Basic Multilingual Plane, which is where nearly all emoji live. So the file has to be UTF-8, and the reader has to know it.
Python writes UTF-8 when you ask. The csv module docs say to pass the encoding argument to open() when writing; on some platforms the default encoding is not UTF-8, so never rely on it.
Add the BOM for Excel. Python's codecs docs describe utf-8-sig as the variant Microsoft introduced for Notepad: on encoding it writes the bytes 0xEF 0xBB 0xBF first, and on decoding it skips them if present. The same docs note that a BOM in UTF-8 is otherwise discouraged. Microsoft's support article on opening CSV UTF-8 files says a UTF-8 CSV opens normally in Excel if it was saved with a BOM; without one, you have to go through Data > Get Data > From Text/CSV. In our export the BOM cost exactly three bytes.
Read it back with utf-8-sig too. If you read a BOM file with plain utf-8, the first header comes back as \ufeffid instead of id, and row["id"] raises KeyError. encoding="utf-8-sig" reads files with or without a BOM, so it is a safe default for reading. In pandas, pass encoding="utf-8-sig" to read_csv for the same reason.
When to skip the BOM. If the CSV feeds a database loader, a Unix pipeline or another program rather than a person in Excel, write plain utf-8. Some loaders treat the BOM as part of the first column name.
IDs: keep 19-digit numbers as text
Every post ID in our sample was 19 digits long. Microsoft's support article on large numbers states that Excel has a maximum precision of 15 significant digits and that digits past the 15th are changed to zero. A double-precision float (JavaScript numbers, pandas float columns, many BI tools) holds exact integers only up to 2^53, about 9.0 x 10^15.
conversation_id has the same problem (993 of 993 changed). Author IDs were safe here because these five organization accounts are old (8 and 10 digits), but newer accounts are not: among the 182 distinct authors of the posts these accounts reposted or quoted, 64 had 19-digit IDs and 79 had IDs longer than 15 digits that Excel would change. Treat author_id as text as well.
On the writer side keep IDs as strings (the API already returns id as a string; do not cast it to int). Some guides suggest writing ="2128..." or a leading apostrophe to force Excel to keep text; that works for Excel only and pollutes the data for every other reader, so we do not recommend it.
On the reader side declare the type: in pandas, dtype={"id": str, "conversation_id": str, "author_id": str}; in Excel, import through Data > From Text/CSV and set those columns to Text before loading (our Excel guide walks through it); in Google Sheets, import and then format the columns as plain text, or keep the IDs with a leading apostrophe; in R's readr, col_types = cols(id = col_character()). Our free Twitter ID finder turns a handle into its numeric ID if you need to check one.
Pagination, duplicates and what a full export costs
/twitter/user/last_tweets returns up to 20 posts a page, newest first, with has_next_page and next_cursor at the top level of the response (not inside data). The first page takes an empty cursor; each following call passes the previous next_cursor. Stop when has_next_page is false or the cursor is empty.
De-duplicate by ID while you write. A post published while you page can shift a boundary and appear on two pages. A seen set of IDs costs nothing and keeps the CSV one row per post; the script below does this.
Write as you go. Writing each page's rows straight to the open file keeps memory flat for long exports and leaves a usable partial file if a run stops. CSV writing is not the slow part: our 993 rows took about 5 milliseconds to write, against seconds of network time.
Time. The five 10-page timelines took 247 seconds in total, about 4.9 seconds a page. That figure is an upper bound: our study client queues every request on this machine at 5 per second across several jobs. Your own rate depends on your account: 0.2 requests a second before the first payment, 20 once paid, 50 on Scale and 500 on Business.
Our side bills 15 credits per post returned, with a 15-credit minimum per request, so a page with nothing new costs $0.00015; there is no per-request cap. The official X API prices are from its pay-per-usage rate card on docs.x.com/x-api/getting-started/pricing, which also caps post reads at 3 million a month. That puts the per-post read price about 33 times apart. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); the current amount is on the pricing page.
File size: CSV against JSON
The 993 posts arrived as 8.0 MB of JSON pages. The 26-column CSV was 449 KB, 5.5% of that, or 463 bytes a row, with the median post text at 161 characters.
The JSON is large because every post repeats the full author profile, the entity offsets, media size variants, card data and any nested repost or quote. The CSV keeps only what you chose. That is also the argument for keeping both: the CSV is for analysis and sharing, the JSON is the record you can re-flatten when you need a column you left out. Gzip the JSON and archive it next to the CSV; our Twitter JSON guide explains the fields you would be dropping.
Reposts carry clipped text. In our sample, 288 of the 332 reposts (86.7%) had a top-level text of the form RT @handle: ... that ended in an ellipsis. If you need the full reposted words, read retweeted_tweet.text, or better, keep reposts as an ID column and export the original post as its own row.
How we collected this
Question. What does a real export of about 1,000 posts look like once flattened to CSV: file size, column fill rates, rows that need quoting, IDs that break as numbers, and export time?
Accounts and endpoint. Five public organization accounts (@NASA, @github, @nvidia, @vercel, @Xbox), 10 pages each of /twitter/user/last_tweets with default settings (replies excluded), newest first. 50 requests returned 993 posts (one account returned 193 on 10 pages). Study cost: about $0.15 at 15 credits per post.
Window. The latest posts of each account at collection time, collected in 2026. Because accounts post at different rates, the sample spans from about five weeks (@Xbox) to well over a year (@vercel).
Method. Each post was flattened to the 26-column schema above and written with Python's csv.DictWriter (default QUOTE_MINIMAL), once as UTF-8 and once as UTF-8 with a BOM, then read back with csv.DictReader to confirm a lossless round trip. ID precision was tested by truncating to 15 significant digits (Excel's limit) and by converting each ID to a double-precision float. The example script below was run against the same collected pages with the HTTP call stubbed out; we did not open the file in Excel ourselves, so the Excel behavior here comes from Microsoft's documentation.
What the sample cannot show. Organization accounts post more links, media and line breaks than many personal accounts, and they rarely use hashtags, so your fill rates and quoting share will differ; replies were excluded; timing includes our own client's queueing.
Privacy. Aggregates only, organization accounts only. The published sample CSV holds 25 organization-authored original posts (no reposts, no quote or reply text from other accounts). Raw responses are not published.
import csv
import os
import sys
import time
from datetime import datetime, timezone
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
# Fixed pacing: 5 s fits 0.2 requests/s before the first payment; 0.1 s is plenty once paid (20/s).
PAUSE_SECONDS = 5.0
COLUMNS = [
"id", "created_at", "author_username", "author_name", "author_id", "author_followers",
"type", "lang", "text", "like_count", "retweet_count", "reply_count", "quote_count",
"view_count", "bookmark_count", "conversation_id", "in_reply_to_id", "in_reply_to_username",
"quoted_tweet_id", "retweeted_tweet_id", "hashtags", "mentions", "expanded_urls",
"media_types", "media_urls", "url",
]
def fetch_timeline(user_name, max_pages=10):
"""Yield posts from a user's timeline, newest first, 20 per page."""
cursor = ""
for _ in range(max_pages):
r = requests.get(
f"{BASE}/twitter/user/last_tweets",
headers=HEADERS,
params={"userName": user_name, "cursor": cursor},
timeout=30,
)
r.raise_for_status()
body = r.json()
if body.get("status") == "error":
raise RuntimeError(body.get("msg"))
yield from (body.get("data") or {}).get("tweets") or []
if not body.get("has_next_page") or not body.get("next_cursor"):
break
cursor = body["next_cursor"]
time.sleep(PAUSE_SECONDS)
def post_type(t):
if t.get("retweeted_tweet") or (t.get("text") or "").startswith("RT @"):
return "repost"
if t.get("isReply"):
return "reply"
if t.get("quoted_tweet"):
return "quote"
return "original"
def flatten(t):
ent = t.get("entities") or {}
media = (t.get("extendedEntities") or {}).get("media") or []
a = t.get("author") or {}
created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
return {
"id": str(t["id"]),
"created_at": created.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"author_username": a.get("userName", ""),
"author_name": a.get("name", ""),
"author_id": str(a.get("id", "")),
"author_followers": a.get("followers", ""),
"type": post_type(t),
"lang": t.get("lang") or "",
"text": t.get("text") or "",
"like_count": t.get("likeCount", ""),
"retweet_count": t.get("retweetCount", ""),
"reply_count": t.get("replyCount", ""),
"quote_count": t.get("quoteCount", ""),
"view_count": t.get("viewCount", ""),
"bookmark_count": t.get("bookmarkCount", ""),
"conversation_id": t.get("conversationId") or "",
"in_reply_to_id": t.get("inReplyToId") or "",
"in_reply_to_username": t.get("inReplyToUsername") or "",
"quoted_tweet_id": (t.get("quoted_tweet") or {}).get("id", ""),
"retweeted_tweet_id": (t.get("retweeted_tweet") or {}).get("id", ""),
"hashtags": "|".join(h.get("text", "") for h in ent.get("hashtags") or []),
"mentions": "|".join(m.get("screen_name", "") for m in ent.get("user_mentions") or []),
"expanded_urls": "|".join(u.get("expanded_url", "") for u in ent.get("urls") or []),
"media_types": "|".join(m.get("type", "") for m in media),
"media_urls": "|".join(m.get("media_url_https", "") for m in media),
"url": t.get("url") or "",
}
def main(user_name, out_path, max_pages=10):
seen = set()
rows = 0
# newline="" lets the csv module handle line breaks inside quoted fields;
# utf-8-sig writes a BOM so Excel detects UTF-8 on double-click.
with open(out_path, "w", encoding="utf-8-sig", newline="") as f:
w = csv.DictWriter(f, fieldnames=COLUMNS) # QUOTE_MINIMAL is the default
w.writeheader()
for t in fetch_timeline(user_name, max_pages):
if t["id"] in seen:
continue
seen.add(t["id"])
w.writerow(flatten(t))
rows += 1
print(f"wrote {rows} rows to {out_path}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], int(sys.argv[3]) if len(sys.argv) > 3 else 10)
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
How do I export tweets to CSV?
Fetch the posts as JSON from an API (for a user's posts, /twitter/user/last_tweets with userName), follow next_cursor until has_next_page is false, flatten each post into fixed columns, and write the rows with a real CSV writer such as Python's csv.DictWriter, on a file opened with newline="" and encoding="utf-8-sig". Keep every ID column as text. The full script is on this page.
Why do my tweet IDs end in 0000 in Excel?
Excel stores up to 15 significant digits and turns the rest into zeros, and post IDs are 19 digits. In our sample, all 993 post IDs changed this way. Import the CSV through Data > From Text/CSV and set the ID columns to Text before loading; the damage cannot be undone after Excel has converted them.
Why are emoji showing as strange characters when I open the CSV?
The program read the UTF-8 file as a legacy code page. Write the file with encoding="utf-8-sig" so it starts with a three-byte BOM; Microsoft's documentation says Excel then opens UTF-8 CSV files normally. Otherwise import through Data > Get Data > From Text/CSV.
Why does my tweets CSV have more lines than tweets?
Post text contains line breaks, and inside a quoted CSV field they are legal. Our 993 posts became 3,589 physical lines. Count rows with a CSV parser (csv.reader, pandas, Excel), not with wc -l or a line loop.
Can I export tweets to CSV without code?
For your own account, X's data archive gives you your posts as a JSON file you can convert. For other accounts or searches, a Google Sheets Apps Script can call the API on a schedule and write rows that you download as CSV. Either way, keep IDs as plain text.
How much does it cost to export 10,000 tweets to CSV?
With our API, posts cost 15 credits each ($0.15 per 1,000), so 10,000 posts are $1.50 over about 500 requests. On the official X API's pay-per-usage rate card a post read is $0.005, so the same 10,000 posts are $50.
Should I keep the JSON as well as the CSV?
Yes. The CSV is small (5.5% of the JSON in our test) but holds only the columns you chose. Archive the gzipped JSON so you can add a column later without fetching the posts again.
Can I export replies to a tweet to CSV?
Yes. Search /twitter/tweet/advanced_search with the query conversation_id:<id> and queryType=Latest, which returns the replies in the thread as a top-level tweets list. Pass each post through the same flatten function; the reply columns (in_reply_to_id, in_reply_to_username) then fill.
Continue
- Python docs: csv module (newline='', QUOTE_MINIMAL default, lineterminator \r\n)
- Python docs: codecs, the utf-8-sig encoding and the BOM
- RFC 4180: Common Format and MIME Type for CSV Files
- Microsoft Support: Opening CSV UTF-8 files correctly in Excel
- TwitterAPI.io docs: Get user last tweets (20 per page, next_cursor)
- X developer docs: X API pricing (pay-per-usage rate card)
- X (Twitter) API overview: endpoints, pricing and limits
- Twitter JSON: every field of a real tweet response
- Twitter API to Excel: Power Query, Python and CSV import
- Twitter (X) dataset export for researchers
- Twitter to Google Sheets with Apps Script
- Analyze X posts with pandas
- Twitter API pagination with next_cursor
- Free Twitter ID finder
- TwitterAPI.io pricing and free starter credits
- 01How to Mute a Conversation on Twitter (X): Mute This Conversation, Step by Step
- 02How to Hide Replies on Twitter (X), and What a Hidden Reply Still Shows
- 03Twitter (X) Ad Examples by Format, With Real Brand Data
- 04Twitter (X) Affiliate Marketing in 2026: Rules, Disclosure and What Link Posts Really Reach
- 05Home Assistant and Twitter (X): Notify, Sensors and Automations
- 06How to Hydrate Tweets: Turn a Twitter (X) Tweet ID Dataset Back Into Full Tweets
- 07Mass Delete Tweets — Bulk API Workflow + Free Tool Options
- 08How to Download Tweets via API — A Python Guide
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.