标签: readlines

来自readlines()的Groovy正则表达式匹配列表

我试图读取一个文本文件并返回所有不以#开头的行.在python中我可以轻松使用列表理解列表

with open('file.txt') as f:
     lines = [l.strip('\n') for l in f.readlines() if not re.search(r"^#", l)]
Run Code Online (Sandbox Code Playgroud)

我想通过Groovy完成同样的事情.到目前为止,我有以下代码,非常感谢任何帮助.

lines = new File("file.txt").readLines().findAll({x -> x ==~ /^#/ })
Run Code Online (Sandbox Code Playgroud)

regex groovy readlines

4
推荐指数
1
解决办法
4644
查看次数

如何使用Python 3中的readlines读取由空格分隔的整数输入文件?

我需要读取一个包含一行整数(13 34 14 53 56 76)的输入文件(input.txt),然后计算每个数字的平方和.

这是我的代码:

# define main program function
def main():
    print("\nThis is the last function: sum_of_squares")
    print("Please include the path if the input file is not in the root directory")
    fname = input("Please enter a filename : ")
    sum_of_squares(fname)

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        items = int(items)
        sum2 += items**2
    print("The sum of the squares is:", sum2)
    infile.close()

# execute main program function
main()
Run Code Online (Sandbox Code Playgroud)

如果每个数字都在它自己的行上,它可以正常工作.

但是,当所有数字都在一个由空格分隔的行上时,我无法弄清楚如何做到这一点.在这种情况下,我收到错误: …

python integer readlines python-3.x

4
推荐指数
1
解决办法
292
查看次数

如何避免使用readlines()?

我需要处理超大的txt输入文件,我通常使用.readlines()来首先读取整个文件,并将其转换为列表.

我知道这确实是内存成本,而且可能很慢,但我还需要利用LIST特性来操作特定的行,如下所示:

#!/usr/bin/python

import os,sys
import glob
import commands
import gzip

path= '/home/xxx/scratch/'
fastqfiles1=glob.glob(path+'*_1.recal.fastq.gz')

for fastqfile1 in fastqfiles1:
    filename = os.path.basename(fastqfile1)
    job_id = filename.split('_')[0]
    fastqfile2 = os.path.join(path+job_id+'_2.recal.fastq.gz') 

    newfastq1 = os.path.join(path+job_id+'_1.fastq.gz') 
    newfastq2 = os.path.join(path+job_id+'_2.fastq.gz') 

    l1= gzip.open(fastqfile1,'r').readlines()
    l2= gzip.open(fastqfile2,'r').readlines()
    f1=[]
    f2=[]
    for i in range(0,len(l1)):
        if i % 4 == 3:
           b1=[ord(x) for x in l1[i]]
           ave1=sum(b1)/float(len(l1[i]))
           b2=[ord(x) for x in str(l2[i])]
           ave2=sum(b2)/float(len(l2[i]))
           if (ave1 >= 20 and ave2>= 20):
              f1.append(l1[i-3])
              f1.append(l1[i-2])
              f1.append(l1[i-1])
              f1.append(l1[i])
              f2.append(l2[i-3])
              f2.append(l2[i-2])
              f2.append(l2[i-1])
              f2.append(l2[i])
    output1=gzip.open(newfastq1,'w')
    output1.writelines(f1)
    output1.close()
    output2=gzip.open(newfastq2,'w') …
Run Code Online (Sandbox Code Playgroud)

python list readlines

3
推荐指数
1
解决办法
1565
查看次数

如何在scrapy中读取json文件中的行

我有一个JSON文件存储一些用户信息,包括id,nameurl.json文件如下所示:

{"link": "https://www.example.com/user1", "id": 1, "name": "user1"}
{"link": "https://www.example.com/user1", "id": 2, "name": "user2"}
Run Code Online (Sandbox Code Playgroud)

这个文件是由scrapy蜘蛛写的.现在我想从json文件中读取urls并抓取每个用户的网页.但我无法从json文件加载数据.

这时,我不知道如何获取这些网址.我想我应该首先阅读json文件中的行.我在Python shell中尝试了以下代码:

import json    
f = open('links.jl')    
line = json.load(f)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

Raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1- line 138 column 497(char498-67908)
Run Code Online (Sandbox Code Playgroud)

我在网上做了一些搜索.搜索表明json文件可能存在一些格式问题.但是json文件是使用scrapy管道创建并填充项目的.有没有人知道导致错误的原因是什么?以及如何解决?有关阅读网址的任何建议吗?

非常感谢.

python json scrapy readlines

3
推荐指数
1
解决办法
5712
查看次数

需要帮助理解Microsoft对File.ReadLines和File.ReadAllLines的解释

根据Microsoft对The ReadLinesReadAllLinesmethods 的解释,当您使用时ReadLines,您可以在返回整个集合之前开始枚举字符串集合.使用时ReadAllLines,必须等待返回整个字符串数组,然后才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.

当他们说:

1 - "当你使用ReadLines时,你可以在返回整个集合之前开始枚举字符串集合. "如果编写下面的代码行,那么这不意味着ReadLines方法执行结束并且整个集合是返回并存储在变量filedata中?

IEnumerable<String> filedata = File.ReadLines(fileWithPath)
Run Code Online (Sandbox Code Playgroud)

2 - "当你使用时ReadAllLines,你必须等待返回整个字符串数组才能访问数组 ".这是否意味着,在下面的代码片段中,如果读取一个大文件,那么如果在读取文件后立即使用数组变量hugeFileData将不会拥有所有数据?

string[] hugeFileData = File.ReadAllLines(path)
string i = hugeFileData[hugeFileData.length-1];
Run Code Online (Sandbox Code Playgroud)

3 - "当您使用非常大的文件时,ReadLines可以更高效 ".如果是这样,那么在读取大文件时,以下代码是否有效?我相信第二行和第三行下面的代码会读取文件两次,如果我错了,请纠正我.

string fileWithPath = "some large sized file path";
string lastLine = File.ReadLines(fileWithPath).Last();
int totalLines = File.ReadLines(fileWithPath).Count();
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中两次在同一文件上调用ReadLines的原因是当我尝试下面的代码时,我TextReader在下面的代码片段的第3行上得到了一个异常"无法从关闭状态读取".

IEnumerable<String> filedata = File.ReadLines(fileWithPath);
string lastLine = filedata.Last();
int totalLines = filedata.Count();
Run Code Online (Sandbox Code Playgroud)

c# readlines file.readalllines

3
推荐指数
1
解决办法
436
查看次数

Python限制readlines的换行符()

我试图分裂它采用的新行字符的混合文本LF,CRLFNEL.我需要最好的方法将NEL字符排除在场景之外.

是否有选项可以指示readlines()在分割线条时排除NEL?我或许可以在循环中read()仅进行匹配LFCRLF分割点.

有没有更好的解决方案?

我打开文件codecs.open()打开utf-8文本文件.

在使用时readlines(),它以NEL字符分割:

会话截图

文件内容是:

"u'Line 1 \\x85 Line 1.1\\r\\nLine 2\\r\\nLine 3\\r\\n'"
Run Code Online (Sandbox Code Playgroud)

python readlines python-2.7

3
推荐指数
1
解决办法
1635
查看次数

codecs.ascii_decode(input,self.errors)[0] UnicodeDecodeError:'ascii'编解码器无法解码318位的字节0xc2:序号不在范围内(128)

我试图打开并读取包含大量文本的.txt文件.下面是我的代码,我不知道如何解决这个问题.任何帮助将非常感激.

file = input("Please enter a .txt file: ")
myfile = open(file)
x = myfile.readlines()
print (x)
Run Code Online (Sandbox Code Playgroud)

当我输入.txt文件时,这是完整的错误消息显示如下:

line 10, in <module> x = myfile.readlines()
line 26, in decode return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 318: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

python ascii decode readlines

3
推荐指数
1
解决办法
7046
查看次数

在Python中打印多个文件的特定行

我有30个文本文件,每个30行.出于某种原因,我需要编写一个打开文件1的脚本,打印文件1的第1行,关闭它,打开文件2,打印文件2的第2行,关闭它,依此类推.我试过这个:

import glob

files = glob.glob('/Users/path/to/*/files.txt')             
for file in files:
    i = 0
    while i < 30:
        with open(file,'r') as f:
            for index, line in enumerate(f):
                if index == i:
                    print(line)
                    i += 1
                    f.close()
            continue 
Run Code Online (Sandbox Code Playgroud)

显然,我收到以下错误:

ValueError:关闭文件的I/O操作.

因为f.close()的事情.如何只读取所需的行后,如何从文件移动到下一个文件?

python enumerate readlines python-3.x

3
推荐指数
1
解决办法
906
查看次数

Apache Common FileUtils readLines 方法歧义调用

在尝试使用 Android Studio 使用 Apache commons IO 第三方 API 时,我偶然发现了这个问题。

基本上,当我尝试调用FileUtils.readLines()方法时,有 3 个选项:

  • readLines(File file) >>>> 已弃用
  • readLines(文件文件,字符串编码)
  • readLines(文件文件,字符集编码)

第一个选项已经被弃用,这意味着我不应该再使用它,所以我只输入readLines(file,null)但是,现在的问题是 Android Studio 不知道我使用哪个 readLines() 方法签名m 使用是因为readLines(file,null)对第二个和第三个方法签名都有效。

下面的屏幕截图进一步解释了我的意思:

在此处输入图片说明

任何人都可以请教我吗?如何告诉 Android Studio 我想用于FileUtils.readLines()的特定方法签名?

apache io android readlines fileutils

3
推荐指数
1
解决办法
2225
查看次数

在文本文件上一次迭代两行,而在 python 中一次递增一行

假设我有一个文本文件,其中包含以下内容:

a
b
c
d
e
Run Code Online (Sandbox Code Playgroud)

我想迭代该文件的每一行,但在此过程中还要获取第一行后面的行。我已经尝试过这个:

with open(txt_file, "r") as f:
    for line1, line2 in itertools.zip_longest(*[f] * 2):
        if line2 != None:
            print(line1.rstrip() + line2.rstrip())
        else:
            print(line1.rstrip())
Run Code Online (Sandbox Code Playgroud)

它返回类似:

ab
cd
e
Run Code Online (Sandbox Code Playgroud)

但是,我希望有这样的输出:

ab
bc
cd
de
e
Run Code Online (Sandbox Code Playgroud)

有人知道如何实现这一目标吗?提前致谢!

python iteration text readlines txt

3
推荐指数
1
解决办法
420
查看次数