SORU
1 Mart 2009, Pazar


Bir dize sol parçası kaldırmak için nasıl Python -?

Bir dize c:\path değişebilir sayede path=c:\path örneğin, dosyaları arar bazı basit python kodu var. Geçerli kod:

def findPath( i_file) :
  lines = open( i_file ).readlines()
  for line in lines :
    if line.startswith( "Path=" ) :
      return # what to do here in order to get line content after "Path=" ?

Path= sonra Dize bir metin elde etmek için basit bir yolu nedir? Basit bir yöntem, kilitler, yansıma ya da diğer gizli şeyler olmadan var mı ?

CEVAP
1 Mart 2009, Pazar


Bir dizeden öneki kaldırın

# ...
if line.startswith(prefix):
   return line[len(prefix):]

str.partition()) ayırıcı ilk geçtiği konusunda ikiye bölünmüş

def findvar(filename, varname="Path", sep="=") :
    for line in open(filename):
        if line.startswith(varname   sep):
           head, sep_, tail = line.partition(sep) # instead of `str.split()`
           assert head == varname
           assert sep_ == sep
           return tail

Ayrıştırma-INI ConfigParser ile dosya

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present

path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation

Diğer seçenekleri

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Hey Nadine

    Hey Nadine

    24 Kasım 2006
  • LIVESTRONG.COM

    LIVESTRONG.C

    5 EKİM 2005
  • NextGenWindows

    NextGenWindo

    8 Kasım 2011