在文本文件中查找一行。

huangapple go评论67阅读模式
英文:

Find a line in a text file

问题

我试图制作一个项目你输入一个数字它会告诉你在另一个文件中的那一行有什么但它就是不起作用

我只尝试了这个但我的代码是

```python
a = input('你想读取哪一行的文件:')
file = open('newfile.txt', 'r')
print(file.readlines(a))
file.close()

<details>
<summary>英文:</summary>

Im trying to make a project where you type in a number and it tells you what is on that line on a separate file but it just won&#39;t work.

I&#39;ve only tried this but my code is:

a = input('what file line would you like to read: ')
file = open('newfile.txt', 'r')
print(file.readlines(a))
file.close()


</details>


# 答案1
**得分**: 2

`readlines` 返回一个包含文件中所有行的 **列表**。要获取特定行,您可以尝试:

```python
line_number = int(input("您想要读取哪一行:"))
with open("newfile.txt", "r") as file:
    content = file.readlines()
    try:
        print(content[line_number - 1])
    except IndexError:
        print("您输入的行号超出范围")
英文:

readlines returns a list containing all the lines from the file. To get a specific line, you can try :

line_number = int(input(&quot;what file line would you like to read: &quot;))
with open(&quot;newfile.txt&quot;, &quot;r&quot;) as file:
    content = file.readlines()
    try:
        print(content[line_number - 1])
    except IndexError:
        print(&quot;The line number you entered is out of range&quot;)

答案2

得分: 1

你可以使用 linecache.getline 函数。

import linecache

line_number = int(input("你想要读取的行号: "))
line = linecache.getline('YourFile.txt', line_number)

print(line)

当你完成文件操作后,你可以使用 linecache.clearcache() 来释放内存中的文件。

英文:

You can use linecache.getline

import linecache
  
line_number = int(input(&quot;what line would you like to read: &quot;))
line        = linecache.getline(&#39;YourFile.txt&#39;, line_number)
  
print(line)

When you are done with the file, you can use linecache.clearcache() to release the file from memory.

答案3

得分: 1

使用 itertools.islice 的另一种解决方案:

from itertools import islice

a = int(input('您想要读取哪一行文件:    '))

with open('the_file.txt', 'r') as f_in:
    print(*islice(f_in, a - 1, a), end='')
英文:

Another solution, using itertools.islice:

from itertools import islice

a = int(input(&#39;what file line would you like to read:    &#39;))

with open(&#39;the_file.txt&#39;, &#39;r&#39;) as f_in:
    print(*islice(f_in, a - 1, a), end=&#39;&#39;)

答案4

得分: 0

.readlines()只有一个名为"hint"的属性,用法如下:

可选。如果返回的字节数超过提示数字,则不会返回更多行。默认值为-1,表示将返回所有行。

另外,输入返回字符串作为返回值,而"hint"需要是一个整数。

要打开一个文件,请使用"with"语句,像这样,以良好的实践方式读取文件,这样在使用完文件后就不必担心关闭文件。

lines_array = []
with open("newfile.txt", "r") as file:
    for line in file:
        lines_array.append(line)

之后,您可以执行输入部分,

a = input('您想读取哪一行文件:')
print(lines_array[int(a)])
英文:

.readlines() has only one attribute called "hint" which is used as followed:

> Optional. If the number of bytes returned exceed the hint number, no more lines will be returned. Default value is -1, which means all lines will be returned.

also input returns str as return value and "hint" needs to be an integer.

To open a file use the "with" statement like this, for good practice and read the file with this snippet so you don't have to worry about closing the file after using it.

lines_array = []
with open(&quot;newfile.txt&quot;, &quot;r&quot;) as file:
    for line in file:
        lines_array.append(line)

after this you can do the input part,

a = input(&#39;what file line would you like to read:    &#39;)
print(lines[int(a)])

答案5

得分: 0

lineno = int(input('行号(从1开始):')) # 这里应该真正验证输入

with open('/Volumes/G-Drive/foo.txt') as foo:
    line = None
    for _ in range(lineno):
        if not (line := foo.readline()):
            # 文件结束
            print('文件中没有足够的行')
            break
    else:
        print(line)
英文:

Without importing any additional modules and also (potentially) not reading the entire file:

lineno = int(input(&#39;Line number (base 1): &#39;)) #&#160;should really validate the input here

with open(&#39;/Volumes/G-Drive/foo.txt&#39;) as foo:
    line = None
    for _ in range(lineno):
        if not (line := foo.readline()):
            # EOF
            print(&#39;Not enough lines in the file&#39;)
            break
    else:
        print(line)

huangapple
  • 本文由 发表于 2023年7月23日 23:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定