2014-02-10 30 views
0

請您需要您的幫助,我想將compy中的某些特定行從compy複製到另外兩個文件。 變量n和p是全局的。 這裏是我的代碼:我發現文件末尾是空的,python

def files(): 
    i = 1 
    X = 1 
    f90 = open('C:\Users\Homura\Desktop\python\data90.txt' , 'w') 
    f10 = open('C:\Users\Homura\Desktop\python\data10.txt' , 'w') 
    f = open('C:\Users\Homura\Desktop\python\TData.txt' , 'r') 
    while True: 
     line = f.readline() 
     if line.startswith('0'): 
      while i <= n: # taking 90% of negative tweets and writing them in f90 
       f90.write(line) 
       i += 1 
      while i != n: #putting the rest of the negative tweets (10%) in the f10 file 
       f10.write(line) 
       i += 1 
     elif line.startswith('1'): 
      while (x <= p): # taking 90% of positive tweets and writing them in f90 
       f90.write(line) 
       x += 1 
      while (x != p): #putting the rest of the positive tweets (10%) in the f10 file 
       f10.write(line) 
       x += 1     

    f.close() 
    f10.close() 
    f90.close() 
    return f10 , f90 
+0

請解釋一下你的問題,你嘗試過什麼,你想要什麼程序做的,什麼叫「compy」是什麼意思? – Elisha

+1

s/wanrt /想要s/compy/copy? – doctorlove

+0

也許如果你可以從你的文件中提取樣本行,我們可以幫助你更多。 – GMPrazzoli

回答

1

首先,一個小的觀察,你有一個大寫X和小寫x - 他們應該是一樣的嗎?

X = 1 
#... 
x += 1 

接下來,線條不會以您認爲自己開始的字符開頭。 考慮添加一個else,以便在開始時既不輸入0也不輸出1

最後,既然你說while True不清楚如何while循環終止,所以也許它不會和文件永遠不會關閉。嘗試只是在做對文件中的行...(見例如here

試試這個:

for line in f: 
     if line.startswith('0'): 
      while i <= n: # taking 90% of negative tweets and writing them in f90 
       f90.write(line) 
       i += 1 
      while i != n: #putting the rest of the negative tweets (10%) in the f10 file 
       f10.write(line) 
       i += 1 
     elif line.startswith('1'): 
      while (x <= p): # taking 90% of positive tweets and writing them in f90 
       f90.write(line) 
       x += 1 
      while (x != p): #putting the rest of the positive tweets (10%) in the f10 file 
       f10.write(line) 
       x += 1   
     else: 
      print "Unmatched line ", line 

編輯

上述所有假設你已經成功地打開輸入文件確定。

" The backslash() character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences"

docs

您可以使用輸入文件與反斜線: 例如

f = open('C:\Users\Homura\Desktop\python\TData.txt' , 'r') 

嘗試改變這一個原始字符串

f = open(r'C:\Users\Homura\Desktop\python\TData.txt' , 'r') 
+0

非常感謝您的幫助,但不起作用文件「。\ first.py」,第64行 if line.startswith('0'): ^ IndentationError:預期有縮進塊 – kad

+0

縮進錯誤通常意味着您有一個標籤和空格的混亂。 – doctorlove

+0

我複製了你給我的東西,我有這個問題,我不認爲我們需要縮進,但是Python知道wayyy更好:D – kad