如何将文本文件读入Python中的字符串变量?

时间:2022-10-25 07:11:38

I use the following code segment to read a file in python

我使用下面的代码段来读取python中的文件。

with open ("data.txt", "r") as myfile:
    data=myfile.readlines()

input file is

输入文件

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

and when I print data I get

当我打印数据的时候。

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

As I see data is in list form. How do I make it string. And also how do I remove "\n", "[", and "]" characters from it ?

如我所见,数据是以列表形式出现的。如何使它成为字符串。还有,如何删除“\n”、“[”和“]”字符?

17 个解决方案

#1


792  

You could use:

您可以使用:

with open('data.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')

#2


414  

use read(), not readline()

使用read(),而不是readline()

with open('data.txt', 'r') as myfile:
  data = myfile.read()

#3


35  

Read from file in one line

从文件中读取一行。

str = open('very_Important.txt', 'r').read()

#4


29  

The simple way:

简单的方法:

file = open('data.txt', 'r')
text = file.read().strip()
file.close()

#5


24  

with open("data.txt") as myfile:
    data="".join(line.rstrip() for line in myfile)

join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.

join()将会加入一个字符串列表,而没有参数的rstrip()将从字符串的末尾减少空白,包括换行。

#6


4  

It's hard to tell exactly what you're after, but something like this should get you started:

很难确切地说出你到底想要什么,但是这样的事情会让你开始:

with open ("data.txt", "r") as myfile:
    data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])

#7


4  

I have fiddled around with this for a while and have prefer to use use read in combination with rstrip. Without rstrip("\n"), Python adds a newline to the end of the string, which in most cases is not very useful.

我已经摆弄了一段时间了,更喜欢使用与rstrip结合使用的阅读。在没有rstrip(“\n”)的情况下,Python在字符串的末尾添加了一条新行,在大多数情况下都不是很有用。

with open("myfile.txt" as f:
    file_content = f.read().rstrip("\n")
    print file_content

#8


2  

You can also strip each of the line and concatenate into a final string.

您还可以将每条线连接起来,并将其连接到最后一个字符串中。

myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
    data = data + line.strip();

This would also work out just fine.

这样做也很好。

#9


1  

f = open('data.txt','r')
string = ""
while 1:
    line = f.readline()
    if not line:break
    string += line

f.close()


print string

#10


1  

I don't feel that anyone addressed the [ ] part of your question. When you read each line into your variable, because there were multiple lines before you replaced the \n with '' you ended up creating a list. If you have a variable of x and print it out just by

我觉得没有人对你的问题有任何看法。当你把每一行都读到你的变量中,因为在你把\n替换为“你最终创建了一个列表”之前有多行。如果你有一个x的变量并把它打印出来。

x

x

or print(x)

或打印(x)

or str(x)

或str(x)

You will see the entire list with the brackets. If you call each element of the (array of sorts)

您将看到整个列表的括号。如果你调用数组中的每个元素

x[0] then it omits the brackets. If you use the str() function you will see just the data and not the '' either. str(x[0])

x[0]然后省略了括号。如果使用str()函数,您将只看到数据,而不是“两者”。str(x[0])

#11


1  

python3: Google "list comphrension" if the square bracket syntax is new to you.

如果方括号语法对您来说是新的,那么就可以使用python3:谷歌“list comphrension”。

 with open('data.txt') as f:
     lines = [ line.strip( ) for line in list(f) ]

#12


1  

I'm surprised nobody mentioned splitlines() yet.

我很惊讶没有人提到splitlines()。

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()

Variable data is now a list that looks like this when printed:

变量数据现在是这样的列表:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

Note there are no newlines (\n).

注意没有新行(\n)。

At that point, it sounds like you want to print back the lines to console, which you can achieve with a for loop:

在这一点上,听起来好像你想要打印回控制台,你可以用for循环来实现:

for line in data:
    print line

#13


0  

This works: Change your file to:

这是可行的:将您的文件更改为:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

Then:

然后:

file = open("file.txt")
line = file.read()
words = line.split()

This creates a list named words that equals:

这将创建一个名为单词的列表,它等于:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

That got rid of the "\n". To answer the part about the brackets getting in your way, just do this:

去掉了"\n"要回答括号里的问题,可以这样做:

for word in words: # Assuming words is the list above
    print word # Prints each word in file on a different line

Or:

或者:

print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space

This returns:

这将返回:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

#14


0  

with open(player_name, 'r') as myfile:
 data=myfile.readline()
 list=data.split(" ")
 word=list[0]

This code will help you to read the first line and then using the list and split option you can convert the first line word separated by space to be stored in a list.

这段代码将帮助您阅读第一行,然后使用列表和split选项,您可以将第一行单词转换为存储在列表中的空格。

Than you can easily access any word, or even store it in a string.

您可以轻松地访问任何单词,甚至可以将其存储在字符串中。

You can also do the same thing with using a for loop.

你也可以用for循环来做同样的事情。

#15


0  

file = open("myfile.txt", "r")
lines = file.readlines()
str = ''                                     #string declaration

for i in range(len(lines)):
    str += lines[i].rstrip('\n') + ' '

print str

#16


0  

Have you tried this?

你有试过吗?

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)

#17


0  

In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:

在Python 3.5或更高版本中,使用pathlib可以将文本文件内容复制到一个变量中,并在一行中关闭文件:

from pathlib import Path
txt = Path('data.txt').read_text()

#1


792  

You could use:

您可以使用:

with open('data.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')

#2


414  

use read(), not readline()

使用read(),而不是readline()

with open('data.txt', 'r') as myfile:
  data = myfile.read()

#3


35  

Read from file in one line

从文件中读取一行。

str = open('very_Important.txt', 'r').read()

#4


29  

The simple way:

简单的方法:

file = open('data.txt', 'r')
text = file.read().strip()
file.close()

#5


24  

with open("data.txt") as myfile:
    data="".join(line.rstrip() for line in myfile)

join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.

join()将会加入一个字符串列表,而没有参数的rstrip()将从字符串的末尾减少空白,包括换行。

#6


4  

It's hard to tell exactly what you're after, but something like this should get you started:

很难确切地说出你到底想要什么,但是这样的事情会让你开始:

with open ("data.txt", "r") as myfile:
    data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])

#7


4  

I have fiddled around with this for a while and have prefer to use use read in combination with rstrip. Without rstrip("\n"), Python adds a newline to the end of the string, which in most cases is not very useful.

我已经摆弄了一段时间了,更喜欢使用与rstrip结合使用的阅读。在没有rstrip(“\n”)的情况下,Python在字符串的末尾添加了一条新行,在大多数情况下都不是很有用。

with open("myfile.txt" as f:
    file_content = f.read().rstrip("\n")
    print file_content

#8


2  

You can also strip each of the line and concatenate into a final string.

您还可以将每条线连接起来,并将其连接到最后一个字符串中。

myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
    data = data + line.strip();

This would also work out just fine.

这样做也很好。

#9


1  

f = open('data.txt','r')
string = ""
while 1:
    line = f.readline()
    if not line:break
    string += line

f.close()


print string

#10


1  

I don't feel that anyone addressed the [ ] part of your question. When you read each line into your variable, because there were multiple lines before you replaced the \n with '' you ended up creating a list. If you have a variable of x and print it out just by

我觉得没有人对你的问题有任何看法。当你把每一行都读到你的变量中,因为在你把\n替换为“你最终创建了一个列表”之前有多行。如果你有一个x的变量并把它打印出来。

x

x

or print(x)

或打印(x)

or str(x)

或str(x)

You will see the entire list with the brackets. If you call each element of the (array of sorts)

您将看到整个列表的括号。如果你调用数组中的每个元素

x[0] then it omits the brackets. If you use the str() function you will see just the data and not the '' either. str(x[0])

x[0]然后省略了括号。如果使用str()函数,您将只看到数据,而不是“两者”。str(x[0])

#11


1  

python3: Google "list comphrension" if the square bracket syntax is new to you.

如果方括号语法对您来说是新的,那么就可以使用python3:谷歌“list comphrension”。

 with open('data.txt') as f:
     lines = [ line.strip( ) for line in list(f) ]

#12


1  

I'm surprised nobody mentioned splitlines() yet.

我很惊讶没有人提到splitlines()。

with open ("data.txt", "r") as myfile:
    data = myfile.read().splitlines()

Variable data is now a list that looks like this when printed:

变量数据现在是这样的列表:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

Note there are no newlines (\n).

注意没有新行(\n)。

At that point, it sounds like you want to print back the lines to console, which you can achieve with a for loop:

在这一点上,听起来好像你想要打印回控制台,你可以用for循环来实现:

for line in data:
    print line

#13


0  

This works: Change your file to:

这是可行的:将您的文件更改为:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

Then:

然后:

file = open("file.txt")
line = file.read()
words = line.split()

This creates a list named words that equals:

这将创建一个名为单词的列表,它等于:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

That got rid of the "\n". To answer the part about the brackets getting in your way, just do this:

去掉了"\n"要回答括号里的问题,可以这样做:

for word in words: # Assuming words is the list above
    print word # Prints each word in file on a different line

Or:

或者:

print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space

This returns:

这将返回:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

#14


0  

with open(player_name, 'r') as myfile:
 data=myfile.readline()
 list=data.split(" ")
 word=list[0]

This code will help you to read the first line and then using the list and split option you can convert the first line word separated by space to be stored in a list.

这段代码将帮助您阅读第一行,然后使用列表和split选项,您可以将第一行单词转换为存储在列表中的空格。

Than you can easily access any word, or even store it in a string.

您可以轻松地访问任何单词,甚至可以将其存储在字符串中。

You can also do the same thing with using a for loop.

你也可以用for循环来做同样的事情。

#15


0  

file = open("myfile.txt", "r")
lines = file.readlines()
str = ''                                     #string declaration

for i in range(len(lines)):
    str += lines[i].rstrip('\n') + ' '

print str

#16


0  

Have you tried this?

你有试过吗?

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)

#17


0  

In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:

在Python 3.5或更高版本中,使用pathlib可以将文本文件内容复制到一个变量中,并在一行中关闭文件:

from pathlib import Path
txt = Path('data.txt').read_text()