Я новичок в Python и попробую следующее: я читаю файл из Интернета и хочу разбить его на определенное количество строк. 1. Файл = строка 1 х 2. Файл = строка х + 1 до EOFЧтение файла из Интернета и разбивка на 2
я использую httplib2 прочитать файл из Интернета и раскола, то этот файл в 2. Пробовали с «с», но кажется, что я не могу использовать f.readline() и т. д., когда я читаю файл из Интернета и использую его с помощью «с». Если я открою локальный файл, он отлично работает.
Я пропустил что-то здесь?
Благодарим вас за помощь.
with data_file as f:
#data_file является чтение файла из Интернета
Вот моя функция:
def create_data_files(data_file):
# read the file from the internet and split it into two files
# Loading file give info if the file was loaded from cache or internet
try:
print("Reading file from the Internet or Cache")
h = httplib2.Http(".cache")
data_header, data_file = h.request(DATA_URL) # , headers={'cache-control':'no-cache'}) # to force download form internet
data_file = data_file.decode()
except httplib2.HttpLib2Error as e:
print(e)
# Give the info if the file was read from the internet or from the cache
print("DataHeader", data_header.fromcache)
if data_header.fromcache == True:
print("File was read from cache")
else:
print("File was read from the internet")
# Counting the amount of total characters in the file - only for testing
# print("Total amount of characters in the original file", len(data_file)) # just for testing
# Counting the lines in the file
print("Counting lines in the file")
single_line = data_file.split("\n")
for value in single_line:
value =value.strip()
#print(value) # juist for testing - prints all the lines separeted
print("Total amount of lines in the original file", len(single_line))
# Asking the user how many lines in percentage of the total amount should be training data
while True:
#split_factor = int(input("What percentage should be use as training data? Enter a number between 0 and 100: "))
split_factor = 70
print("Split Factor set to 70% for test purposes")
if 0 <= split_factor <= 100:
break
print('try again')
split_number = int(len(single_line)*split_factor/100)
print("Number of Training set data", split_number) # just for testing
# Splitting the file into 2
training_data_file = 0
test_data_file = 0
return training_data_file, test_data_file
возможно дубликат [В Python, учитывая URL в текстовый файл, то, что является самым простым способ чтения содержимого текстового файла?] (http://stackoverflow.com/questions/1393324/in-python-given-a-url-to-a-text-file-what-is-the-simplest- way-to-read-the-cont) – AHuman