Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

How to get only a part from a string in python

I have a list with the following strings:

total 71708
-rw-rw-rw- 1   gpatwprd        tmwdprd 221     Nov 19 12:36 20181116.Something name.6781773.CSV
-rw-rw-rw- 1   gpatwprd        tmwdprd 221     Nov 19 12:36 20171116.Something name.67885.CSV

And I would like to extract:

  1. Only the filename which starts from 20181116 (or any other data, this is a dynamic number)
  2. Only filenames with .CSV and .XLSX

Note that the filename can be variable in length.

How can I do this in python 3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code will print a list of all the required entries and also a list that has only names of required files. 'data.txt' is the file which has the data to be used. Hope this helps!

fileContent = open('data.txt','r');
readLinesfromContent = fileContent.readlines();

splitLinesforSpace = []
for line in readLinesfromContent:
    splitLinesforSpace.append(line.split())

requiredEntries = []
namesofRequiredFiles = []
for idx, x in enumerate(splitLinesforSpace):
    if len(x) == 10:
        if x[8].startswith('20181116'):
            if x[9].endswith('.CSV') or x[9].endswith('.XLSX'):
                requiredEntries.append(readLinesfromContent[idx])
                x[9] = x[9].split('.')
                #Following gives only names of files
                namesofRequiredFiles.append(x[9][0])

print(requiredEntries)
print(namesofRequiredFiles)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...