简体   繁体   中英

Python - Read TXT File lines --> Array

I need to open a text file with Python and read this Text file line by line to put it into an arrary. Later on I want to write every single content from that array into a database. This is my code so far:

#!/usr/bin/python
# -*- coding: utf8 -*-

#importieren der Module
import MySQLdb
import sys
import re          # regex
import codecs      # utf8 support

# Datei file einlesen
names = []
fo = open("file.txt", "r")
print "Name of file:", fo.name
for line in fo:
    line = line.strip()

fo.close()

How can I do this ? What is the right command to insert the text lines into an array ?

If I'm understanding you correctly, your text file looks something like this:

E YD6567 E YD9876 E YD9867 etc...

And you wish to remove the "E " and just store the "YD####" in a list. Your loop will look like this:

for line in fo:
    names.append(line.replace('E ', '')

The "append" function adds an item to a list. The "replace" function replaces whatever part of the string you specify with whatever else you specify (in this case, replacing "E " with nothing, effectively removing it from the string).

If you would like to store the full line (including "E "), it's as simple as:

for line in fo:
    names.append(line)
lines = []
with open('file.txt', 'r') as f:
    lines = f.readlines()

This should give you a list of all the lines in your code. This assumes that your text file is multi-lined and does not contain all of the text on a single line. If the text IS on a single line you can use this code to create a list of the lines.

splitOn = '\n'
fd = open('file.txt', 'r')
lines = fd.read().split(splitOn)

You can change splitOn to be any character you want to split the string on if there is some other symbol marking the end of lines instead of the newline character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM