Read in certain lines from a .txt file with python

Viewed 52

I have a Example.txt file like the following:

Fu
ih
✌
te
eirt
a
nq
awi
oq
qu
acisrrtr
qopa

My real .txt file is much longer.

Now I want to read in line 2, 5, 8, 11, ... in a list with Python.

I tried to read in every line and take then only the certain lines from the list but the problem is that I can't read in symbols like ✌, and (which occur only in line 3, 6, 9, 12, ...).

I tried the following Python code to do this but it didn't work:

Column1 = []

pfad = r"C:/Users/.../"

with open(pfad + "Example1.txt", "r") as f:
    reader = csv.reader(f, delimiter = '\n')
    for row in reader:
        Column1.append(row[0])

I also tried

f.readlines()

instead of

csv.reader

but it isn't working neither.

Can someone please help me?

Best regards

Fab_Freak

3 Answers
line_numbers = []

With open(“file.txt”, “r”) as f:
    for num in line_numbers:
        data = f.readlines()[num]

Try to use encoding="utf8" in the open function, it is gonna work

Instead you can try this like this.

**Convert txt to csv

**Csv to df

import pandas as pd
df = pd.read_fwf('path_to_text_file_with_emojis.txt')
df.to_csv('output.csv')

df = pd.read_csv('output.csv')
df.columns =['num','text']
one_string = ' '.join(df['text'].tolist())
print(one_string)

output

'Fu ih ✌ te eirt a nq awi oq qu acisrrtr qopa'
Related