简体   繁体   English

Python-读取TXT文件行->数组

[英]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. 我需要使用Python打开文本文件,然后逐行阅读此文本文件,以将其放入文件库中。 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... E YD6567 E YD9876 E YD9867等...

And you wish to remove the "E " and just store the "YD####" in a list. 您希望删除“ E”,而仅将“ YD ####”存储在列表中。 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). “替换”功能将您指定的字符串的任何部分替换为您指定的任何其他内容(在这种情况下,将“ E”替换为任何内容,从而有效地将其从字符串中删除)。

If you would like to store the full line (including "E "), it's as simple as: 如果您想存储完整的行(包括“ E”),则非常简单:

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. 您可以将splitOn更改为要在其上分割字符串的任何字符,如果还有其他符号标记行尾,而不是换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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